In Java, as well as in your life, there two type of exception:
- checked exception that are the expected problems
- unchecked exception, that are the unexpected problems.
As in the life, for the expected events you are prepared because you plain to have that problem. So you are organized to intercept and block that problem. For example, if you are a student, or you have been a student, you know that your teacher could exam you. To avoid a negative
vote, or problem with you parents , you (theoretically) study. If you don’t study enough you could have a bad vote. But basically you are aware.
In Java is exactly the same, apart from the fact that problems are named Exception. You, and also the compiler, know that you can expect an exception calling a method and then you prevent that exception intercepting it with a try-catch-finally block.
int vote;
try{
vote=teacher.exams(you);
}
catch(NoStudiedException nse){
vote=VOTE.Very_Bad;
}
finally{
register.setVote(you,vote);
}
In Java you are aware because exists the throws clause that forces you to face up to your problem.
The exams method of Teacher class is like below:
public int exams(Student student) throws NoStudiedException{
…
}
But, unfortunately, there are no just checked exception. We can have also unexpected exception that you and the compiler are not aware, for example RuntimeException, ArrayIndexOutOfBoundException, but above all: NullPointerException.
They are all problems you could never have imagined it could happen to you. They are Unchecked.
All exception under Error and RuntimeException classes are Unchecked
You have to know the difference even because there are some framework that have different behavior based on checked and unchecked events.
For example JPA, that is in charge of transactions, makes an automatic rollback just in case of unchecked exception, BUT doesn’t make the same for the checked ones. It means that, if you use JPA and you want rollback when a CheckedException happens, then you have manually rollback out, adding the clause “rollbackFor=<CheckedException>.class” above the method. If you don’t use JPA and his children/nephew then pretend I did not say anything…