How to exit a program in Java

In Java if we want to terminate the execution of the program then we make use of System.exit(n) method. Let us see important points :

  • System.exit(n) method takes a non zero argument to indicate abnormal termination.
  • System.exit(n) will exit the program irrespective of the operation being performed.
  • If we call System.exit(n) within a try catch block having finally block also, then code between finally block is not executed and program just exits.
  • When we call System.exit(n) then it in turn calls Runtime.getRuntime().exit(n).

Let us look at an example code :

public class SystemExit {

	public static void main(String[] args) {

		System.out.println("Program started");
		
		System.out.println("calling system.exit(1)");
		System.exit(1);
		
		System.out.println("Program ended");
		
	}

}

Output

Program started
calling system.exit(2)

Let us look at an example with try-catch and finally blocks:

public class SystemExit {

	public static void main(String[] args) {

		System.out.println("Program started");
		
		try 
		{
			System.out.println("calling system.exit(1)");
			System.exit(1);
		}
		catch(Exception e) {
			System.out.println("Exception caught");
		}
		finally {
			System.out.println("Inside finally block");
		}
		
		System.out.println("Program ended");
		
	}

}

Output

Program started
calling system.exit(1)

It can be observed from the above code that even finally block is not executed when we called System.exit(1).

Leave a Comment