Java Reference
In-Depth Information
System.out.println("-------------------------------");
try {
System.out.println("Inside try block - 3.");
}
finally {
System.out.println("Inside finally block - 3.");
}
System.out.println("-------------------------------");
try {
System.out.println("Before executing System.exit().");
System.exit(0);
System.out.println("After executing System.exit().");
}
finally {
// This finally block will not be executed
// because application exits in try block
System.out.println("Inside finally block - 4.");
}
}
}
Before dividing x by y.
Inside catch block - 1.
Inside finally block - 1.
-------------------------------
Before setting z to 2449.
After setting z to 2449.
Inside finally block - 2.
-------------------------------
Inside try block - 3.
Inside finally block - 3.
-------------------------------
Before executing System.exit().
The first try-catch-finally block attempts to perform a divide-by-zero operation on an integer. The expression
x/y throws an ArithmeticException and control is transferred to the catch block. The finally block is executed after
the catch block finishes. Note that the second message in the try block is not printed because once an exception is
thrown, the control jumps to the nearest matching catch block and the control never goes back to the try block again.
The second try-catch-finally block is an example where the try block finishes normally (without throwing an
exception). After the try block finishes, the finally block is executed.
The third try-finally block is simple. The try block finishes normally, and then the finally block is executed.
The fourth try-finally block demonstrates an exceptional case when a finally block is not executed. The
try block exits the application by executing the System.exit() method. The application stops executing when the
System.exit() method is called without executing the associated finally block.
Search WWH ::




Custom Search