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 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:
UpperCamelCase
( fruit fr =...
-> Fruit fr =...
) 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.