Thank you very much for your elaborate response!
I think I understand when you have to throw an checked exception and what is meant by "recovery" for an exceptional situation. In the example you give with a FileNotFoundException, that would be a "recovery" for an checked exception as you say. OK, so much for checked exceptions.
Now moving on to Runtime exceptions.
You state:
admin wrote:Now, coming to the explanation that you've mentioned, it is not saying that if you get an unchecked exception you cannot recover from it. It is saying that if you encounter a situation from which you cannot recover, it is ok to throw a runtime exception to the caller.
Below, I've marked my 3 most important sentences with A), B) and C).
What I don't really understand is:
A)
If you want to throw a Runtime exception, WHEN do you (as you say) "encounter a situation from which you CANNOT recover"?
To me it seems that this never happens, or at least almost never happens.
B)
And I also don't understand WHICH Runtime exceptions would be thrown when you "encounter a situation from which you CANNOT recover"?
I mean, you can easily "recover" from Runtime exceptions such as a NullPointer-, an ArrayIndexOutOfBounds, an Arithmetic- or a ClassCastException by using a try-catch. Admittedly, these Runtime exceptions are thrown by the JVM. But Runtime exceptions thrown by the programmer such as an IllegalArgument- or IllegalStateException can also be "recovered" with a try-catch, can they not? So which Runtime exceptions are we talking about that can be thrown when you "encounter a situation from which you cannot recover"?
By the way, I think you CAN foresee Runtime exceptions as well, you just have to take the time to examine your code more thoroughly.
A handicap for my understanding of the subject is - I think - that I've no real programming experience apart from writing hundreds of really small programs to test out code and studying hard for the Java OCA SE 7 exam. But I've thoroughly read and thought about the explanation, your answer, the link you provided plus several other documents on the subject, and on that basis my solution now for Runtime exceptions is the following:
C)
You CAN easily "recover" from most if not all Runtime exceptions with a try-catch (and you CAN foresee them as well),
BUT it is not REASONABLY expected of you to do so because Runtime exceptions are the result of an internal / programming problems. Therefore, if you encounter a Runtime exception you can best correct the programming mistake instead of putting a try-catch around it.
Furthermore, Runtime exceptions in a typical program are numerous so catching all of them would (drastically) reduce the clarity of your code.
These are the 2 reasons why you cannot be REASONABLY be expected to catch Runtime exceptions.
Am I correct in my assessment of Runtime exceptions?
Thank you in advance!