finally Block in Exception (JAVA)

Ravi Chandola
Javarevisited
Published in
2 min readDec 28, 2022

To ensure that all the states of a program get executed, we are handling the exception by writing a try-and-catch block.

There are some cases in which the statement after the catch block will not be executed :

1. When you have a return statement inside the try or catch block

2. When an exception occurs in a try block and a matching catch block isn’t available.

3. when we hard push the code to execute from the try block System.exit(0);

When you want to execute statements after the catch block always without fail then you have to place those statements inside the finally block.

The runtime system always executes the statement within the finally block regardless of what happens in the try block

public class TestFinallyBlock2{    
public static void main(String args[]){

try {

System.out.println("Inside try block");

//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}

//handles the Arithmetic Exception / Divide by zero exception
catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}

//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of the code...");
}
}

System.exit(0)

System.exit(0) is a method in the java.lang.System class that is used to terminate the current Java virtual machine. It takes an integer argument, which represents the exit status of the virtual machine. A status of 0 indicates that the virtual machine terminated normally, while a non-zero status indicates that an error occurred.

Here is an example of how System.exit(0) can be used in a Java program:

public class Main {
public static void main(String[] args) {
// some code here
System.exit(0);
}
}

When the System.exit(0) method is called, the Java virtual machine will terminate immediately, and any remaining code in the main method will not be executed.

It’s important to note that calling System.exit(0) will also cause any non-daemon threads that are running in the virtual machine to be stopped abruptly. This can lead to unexpected behavior and should be used with caution.

In general, it is recommended to use System.exit(0) only as a last resort, when it is necessary to terminate the virtual machine for some reason. In most cases, it is better to allow the virtual machine to terminate naturally when the main method finishes executing.

--

--

Ravi Chandola
Javarevisited

As a technology enthusiast, I have a passion for learning and sharing my knowledge with others. https://www.linkedin.com/in/ravi-chandola-304522133