try {
fruit fr = (fruit) p;
System.exit(0);
} catch (Exception e) {
System.out.println("not the right object");
} finally {
System.out.println("finablock");
}
why in this case System.exit(0) didn't terminate the action and I got the two displays from the catch and the finally blocks?
If an
Exceptionis thrown, the execution immediately returns from the surrounding block, (re)-throwing saidException. If a matchingcatch-block is found during traversing up the call stack, thiscatch-block is executed, from here on, execution resumes normally. Allfinally-blocks on the way up the call stacks are executed, in the order they are encountered.For the example, this means that if
throws an
Exception, thenSystem.exit(0);is not executed, but the execution continues with the body of thecatch (Exception e)-block. And due to the semantics offinally, this block is executed just before the method returns.Some remarks on the code:
UpperCamelCase(fruit fr = ...->Fruit fr = ...)System.exit(...), then we should set a value!= 0since this is the exit code of the program. A value of0signals that the application terminated normally (which is most likely not true)