tutorial, no_image, java,

Java - no_image

Upendra Upendra Follow Jan 23, 2025 · 5 mins read
Java - no_image
Share this

try-catch-finally

Java try, catch and finally blocks help in writing the application code which may throw exceptions in runtime and gives us a chance to either recover from exceptions by executing alternate application logic or handle the exception gracefully to report back to the user.1. The three blocks are used in the following way:

  • The try block is used to specify a block of code that may throw an exception;
  • The catch block is used to handle the exception if it is thrown;
  • The finally block is used to execute the code after the try and catch blocks have been executed.2

The following code snippet shows how to use these blocks:3

public class Main {
   public static void main(String[] args) {
       try {
          // Code that may throw an exception
       } catch (Exception e) {
          // Code to handle the exception
       } finally {
          // Code that is always executed
       }
   }
}

try

The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. In general, a try block looks like the following:

try {
    code
}
catch and finally blocks . . .

The segment in the example labeled code contains one or more legal lines of code that could throw an exception. If an exception occurs within the try block, that exception is handled by an exception handler associated with it. You should always have an exception handler - either catch or finally blocks, or both together.

catch

catch block is used to handle the exception by declaring the type of exception within the parameter. The declared exception must be a subclass of the Throwable class:

try {
    // Code that may throw an exception
} catch (IOException e) {
    // Handle exception
}

Rules for catch block:

  • More than one catch block can be written;
  • The catch blocks should immediately follow the try block;
  • The catch blocks should all follow each other, without any other statements or blocks in between them.4

An application can go wrong in N different ways. That’s why we can associate multiple catch blocks with a single try block. In each catch block, we can handle one or more specific exceptions in a unique way.

When one catch block handles the exception, the next catch blocks are not executed. Control shifts directly from the executed catch block to execute the remaining part of the program:5

try {
    //code
}
catch(NullPointerException e) {
    //handle exception
}
catch(NumberFormatException e) {
    //handle exception
}
catch(Exception e) {
    //handle exception
}

The good approach is catch the most specific exception first.

finally

You can attach a finally-clause to a try-catch block. The code inside the finally clause will always be executed, even if an exception is thrown from within the try or catch block. If your code has a return statement inside the try or catch block, the code inside the finally-block will get executed before returning from the method. Here is how a finally clause looks:

 public void openFile() {
    FileReader reader = null;
      try {
        reader = new FileReader("someFile");
        int i=0;
        while(i != -1) {
          i = reader.read();
          System.out.println((char) i );
        }
      } catch (IOException e) {
          //do something clever with the exception
      } finally {
        if (reader != null) {
           try {
            reader.close();
           } catch (IOException e) {
            //do something clever with the exception
           }
      }
        System.out.println("--- File End ---");
      }
}

No matter whether an exception is thrown or not inside the try or catch block the code inside the finally-block is executed. The example above shows how the file reader is always closed, regardless of the program flow inside the try or catch block.

Note: If an exception is thrown inside a finally block, and it is not caught, then that finally block is interrupted just like the try-block and catch-block is. That is why the previous example had the reader.close() method call in the finally block wrapped in a try-catch block:

} finally {
    if(reader != null) {
        try {
            reader.close();
        } catch (IOException e) {
            //do something clever with the exception
        }
    }
        System.out.println("--- File End ---");
}

Note: The finally block may not execute if the JVM exits while the try or catch code is being executed.6

Links

Java try catch finally

How to use the try, catch, and finally blocks in Java

Try-Catch and Finally Block in Java

Basic try-catch-finally Exception Handling in Java

Lesson: Exceptions

Further reading

Java trycatch

Try, Catch and Finally in Java

Best practices for using try-catch blocks to handle exceptions

credit goes to @swayangjit
Join Newsletter
Get the latest news right in your inbox. We never spam!
Upendra
Written by Upendra Follow
Hi, I am Upendra, the author in Human and machine languages,I don't know to how 3 liner bio works so just Connect with me on social sites you will get to know me better.