FastFoodCoding

Login


Connect with one of the following accounts





Login

Please wait while we redirect...

Views: 116   



The java.lang.System.exit() method terminates the currently running JVM (Java Virtual Machine).

Method Declaration

public static void exit(int status)

exit(0) : it indicates a successful termination.
exit(1) or exit(-1) or any other non-zero values indicates unsuccessful termination.

In this tutorial, i am going to explain how system.exit() works in java

Scenario 1: When try block contains system.exit() statement and if control reaches the system.exit() statement then control exits from the execution. Before exiting, all the statements are executed which are there before system.exit() statement.

       try {
            System.out.println("Inside try block");
            System.exit(0);
            System.out.println("After system.exit");
        }
        catch (ArithmeticException e) {
            System.out.println("Inside subclass exception catch block");
        }
        catch (Exception e) {
            System.out.println("Inside super class exception catch block");
        }  
        finally{
            System.out.println("Finally block");
        }

Following are some bullet points

  • In the above code "Inside try block" statement will print on the console then control will exit.
  • When JVM is terminated because of system.exit() then the finally block will not be executed,If we have finally block in our code, so in the above code the finally block will not be executed.

Scenario 2: when exception raised in try block before system.exit() statement then control goes to the corresponding catch block and execute it, if any finally block is there then finally block will also execute, but system.exit() statement will not work in this scenario, see the below code snapshot.

       try {
            System.out.println("Inside try block");
            int i =10/0;
            System.exit(0);
            System.out.println("After system exit");
        }
        catch (ArithmeticException e) {
            System.out.println("Inside ArithmeticException  block");
        }
        catch (Exception e) {
            System.out.println("Inside super class exception class block");
        }
        finally{
            System.out.println("Finally block");
        }

Following are some bullet points

  • In the above code "Inside try block" statement will execute and print on console, in the next line exception raise it will go to Arithmetic exception catch block and it will print "Inside Arithmetic Exception block" statement, next finally block will execute.
  • In this scenario system.exit(0) statement not executed.



On By


Top Tutorials

Top Questions

Top Articles

Top Blogs

Top News