Ø When there are multiple nested try...catch...finally, pay special attention to the timing of finally execution. Ø Please read the Embedfinally.java example before running it, observing its output and summarizing it. Ø Special NOTE: When there are multiple layers of nested Finally, exceptions are thrown at different levels and thrown at different locations, which may lead to different finally statement block execution order.
Embedfinally.java Example
public class Embededfinally {
public static void Main (String args[]) {
int result;
try {
System.out.println ("in Level 1");
try {
System.out.println ("in Level 2");
result=100/0; Level 2
try {
System.out.println ("in Level 3");
result=100/0; Level 3
}
catch (Exception e) {
System.out.println ("Level 3:" + E.getclass (). toString ());
}
finally {
System.out.println ("at level 3 finally");
}
result=100/0; Level 2
}
catch (Exception e) {
System.out.println ("Level 2:" + E.getclass (). toString ());
}
finally {
System.out.println ("at level 2 finally");
}
result = 100/0; Level 1
}
catch (Exception e) {
System.out.println ("Level 1:" + e.getclass (). toString ());
}
finally {
System.out.println ("at level 1 finally");
}
}
}
Ø Discrimination: Finally statement block will be executed? Ø Please answer the above questions through the Systemexitandfinally.java sample program
public class Systemexitandfinally {
public static void Main (string[] args)
{
try{
SYSTEM.OUT.PRINTLN ("in Main");
throw new Exception ("Exception is thrown in main");
System.exit (0);
}
catch (Exception e)
{
System.out.println (E.getmessage ());
System.exit (0);
}
Finally
{
System.out.println ("in finally");
}
}
}
The finally statement is not executed!
public class Systemexitandfinally {
public static void Main (string[] args)
{
try{
SYSTEM.OUT.PRINTLN ("in Main");
throw new Exception ("Exception is thrown in main");
System.exit (0);
}
catch (Exception e)
{
System.out.println (E.getmessage ());
System.exit (0);
}
Finally
{
System.out.println ("in finally");
}
}
}
The finally statement is executed!
Therefore, the finally statement block does not necessarily execute! It depends on where the return value is located.
Hands-on brain: Finally