Reputation: 59
In the Code written below although i have not caught the ArithmeticException
,yet the exception is handled automatically and with finally
Block, the content of main()
method is successfully Executed. Whereas if i remove the return statement from finally and make demo as returning void then the program after executing finally
block throws MainThread
Exception
..why is it so?
public class FinallyDemo {
int demo() {
try {
int a=5/0;
}
finally {
System.out.println("Finally Executed");
return 10;
}
}
public static void main(String s[]) {
int a=new FinallyDemo().demo();
System.out.println("Exception Handled");
}
}
Upvotes: 1
Views: 180
Reputation: 12766
Because you return
from the finally
block, the exception is silently disposed. You should never return from a finally block! (Well, almost always never).
From the Java Language Specification:
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
This also means if you threw a different exception, like an IllegalStateException
, from the finally
block, the original exception would also be discarded.
Upvotes: 4