1. When Exception is thrown, the finally block is executed always before the exception is propagated.
See the following example:
try {
System.out.println("TRY-START");
method_that_throws_runtime_exception();
System.out.println("TRY-STOP");
} finally {
System.out.println("FINALLY");
}
the result is: TRY-START FINALLY and then the information about the runtime exception.
------------------------------------------------------------------------------------------------------------
2. One more thing regarding above scenario. Please, look at this example:
try {
System.out.println("TRY-START");
method_that_throws_runtime_exception(); /e.g. NullPointerException
System.out.println("TRY-STOP");
} finally {
System.out.println("FINALLY");
throws new Exception();
}
The propagated exception is Exception not NullPointerException!
And the result is: TRY-START FINALLY information about Exception.
When the catch block handles exception:
try {
System.out.println("TRY-START");
method_that_throws_runtime_exception(); /e.g. NullPointerException
System.out.println("TRY-STOP");
} catch (Exception e) {
throws new Exception();
} finally {
System.out.println("FINALLY");
}
The propagated exception is Exception not NullPointerException!
And the result is: TRY-START FINALLY information about Exception.
------------------------------------------------------------------------------------------------------------
3. It is correct:
void method() throws FileNotFoundException {}
but this one is incorrect:
try {
} catch (FileNotFoundexception e) {
}
Brak komentarzy:
Prześlij komentarz