-1
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?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

1 Answers1

2

If an Exception is thrown, the execution immediately returns from the surrounding block, (re)-throwing said Exception. If a matching catch-block is found during traversing up the call stack, this catch-block is executed, from here on, execution resumes normally. All finally-blocks on the way up the call stacks are executed, in the order they are encountered.

For the example, this means that if

fruit fr = (fruit) p;

throws an Exception, then System.exit(0); is not executed, but the execution continues with the body of the catch (Exception e)-block. And due to the semantics of finally, this block is executed just before the method returns.


Some remarks on the code:

  • Class names in java should be written in UpperCamelCase (fruit fr = ... -> Fruit fr = ...)
  • If we want to terminate the application abnormally through System.exit(...), then we should set a value != 0 since this is the exit code of the program. A value of 0 signals that the application terminated normally (which is most likely not true)
Turing85
  • 18,217
  • 7
  • 33
  • 58