Wednesday, November 23, 2011

Impact of System.exit on Finally block

Tip: Finally block will not be executed when System.exit () is called within try block.

When System.exit () is called it will shut down the Java Virtual Machine and finally block will not be executed.
class Bar {
 public static void testExit() {
  try {
   System.out.print("Before System.exit(0)");
   System.exit(0);
   System.out.print("After System.exit(0)");
  } finally {
   System.out.print("in finally.");
  }
 }
 public static void main(String[] args) {
  testExit();
 }
}
In above class method testExit () method contains a try-finally block with some print statements, lets run and see what the output is.
Before System.exit(0)
Not only the finally block is skipped, even statement within try block also did not execute. Like we said earlier, System.exit(0) is a hard shut-down of JVM, no statement will be executed after that.

Available in Android Market

No comments:

Post a Comment