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)