finally block with System.exit()

As you know exit() is a method used to terminates the current Java virtual machine running on the system. If you are using this method in your program, then the compiler will not execute the finally block.

public class UseOfExitMethodWithFinallyBlock
{  
  public static void main(String args[])
  {  
  	try
  	{   
		System.out.println("This code is inside in the try block");  
		System.out.println("Rest code inside the try block"); 
		System.exit(0); 
  	}
	catch(Exception e)
	{
		e.printStackTrace();
               System.out.println("If any exception raised in try block then catch block 
               will execute");
	}	
  	finally
	{
		System.out.println("This is finally block"); 
	}
	   //rest code of the program   
  	 System.out.println("This code is outside from the try block");  
  }  
}  

Output: This code is inside in the try block Rest code inside the try block

Leave a Comment