1.

If I write System.exit(0); at the end of the try block, will the finally block still execute?

Answer»

No, the finally block will not EXECUTE. The System.exit() method is a predefined method of the java.lang package. It exits the current program by termination of the running of Java Virtual Machine.

The System.exit() method has a status code represented by an integer value. Usually the status code is 0. A non-zero status code means UNUSUAL termination of the Java program.

The syntax for the exit method in the java.lang package is as follows is as follows

public static void exit(int status_code);

The finally block in Java usually executes everything irrespective of what is written in the try and catch block. An aberration is made when the System.exit() function is written in the try block.

For example,

public class Example {    public static void main(String[] args)    {        try        {         System.out.println("In try block");         System.exit(0);         int a=1/0;        }        catch(ArithmeticException E)        {            System.out.println("EXCEPTION Caught");        }        finally        {            System.out.println("In finally block");        }    } }

The output is as follows:

$javac Example.java $java Example In try block


Discussion

No Comment Found