Java try-catch block

In Java, we handle exceptions using the try-catch block. With the try block, we surround the code that can throw an exception, and in the catch block, we write the code that will be executed in case an error actually occurs in the try block.

try {
     //statements that may cause an exception
} catch (some exception object, e.g. NullPointerException e)‏ {
     //error handling code
}

Examples of handling exceptions using try-catch block

Example 1:

class Test {

  public static void main(String[] args) {

    try {
      int a = 0;
      int b = 10;
      int c = b / a; // we know that this line will throw an exception -> ArithmeticException
                     // so we surround it with try-catch block
    } catch (ArithmeticException e) {
      System.out.println("Exception occurred, we tried to divide a number by zero!");
    }
  }
}
Output: Exception occurred, we tried to divide a number by zero!
 
In the example above, we surrounded the code we suspected could throw an exception with a try clause, and in the catch block, we wrote the code that would be executed in that case. This prevents the program from stopping in the event of an error by executing the catch block.
 
We knew that the code could only throw an ArithmeticException and nothing else, so we just put that class in the catch block.

If we have a code that can throw several different exceptions, then we can handle it in two ways:

  1. With one catch block, where we specify inside () braces the Exception class, which is the base class of all exceptions, so we can catch any exception that happens.
  2. With multiple catch blocks, wherein each block we will specify exactly which exception that block should catch.

Example 2: 

Using one catch block to catch all exceptions.

class Test {

  public static void main(String[] args) {

    try {
      int a = 0;
      int b = 10;
      int c = b / a; // this will throw ArithmeticException
    } catch (Exception e) { // this will catch any exception that occur
      System.out.println("Exception occurred!");
    }
  }
}
Output: Exception occurred!

Example 3:

The below code example can throw 2 exceptions. The catch block will catch the first exception that occurs.

class Test {

  public static void main(String[] args) {

    try {
      Test testReference = null;
      int a = 0;
      int b = 10;
      System.out.println(testReference.toString()); // this will throw NullPointerException, which will be caught by the catch block
      int c = b / a; // this will throw ArithmeticException
    } catch (Exception e) { // this will catch any exception that occur
      System.out.println("Exception occurred!");
    }
  }
}
Output: Exception occurred!

Multiple catch blocks

The exception that occurs first will be caught with the corresponding catch block.

Example 1:

class Test {

  public static void main(String[] args) {

    try {
      Test testReference = null;
      int a = 0;
      int b = 10;
      System.out.println(testReference.toString()); // this will throw NullPointerException
      int c = b / a; // this will throw ArithmeticException
    } catch (ArithmeticException ae) {
      System.out.println("ArithmeticException occurred!");
    } catch(NullPointerException ne) {
      System.out.println("NullPointerException occurred!");
    } catch (Exception e) {
      System.out.println("Exception occurred!");
    }
  }
}
Output: NullPointerException occurred!
 
Note the above order of catch blocks. If we first put a block that accepts the Exception class, then it would execute no matter which exception occurred first. That is why there is a rule in Java that catch blocks should be placed from the most specific to the most general.

Nested try-catch blocks

When a try-catch block is present in another try block, then it is called the nested try-catch block. If an exception occurs in the nested try block and there is no corresponding catch block, the catch blocks of the parent try block will be inspected. If the appropriate catch block is found in the parent try block, then it will be executed, and if it is not found there either, then the system-generated message would be shown for the exception.

Syntax of nested try-catch block:

try {
   statement 1;
   statement 2;
   
  // nested try-catch block
   try {
      statement 3;
      statement 4;
   }
   catch(Exception e1) {
       // ...
   }
   
}
//Catch block of the parent try block
catch(Exception e3) {
     // ....
}

Examples of nested try-catch blocks

Example 1:

class Test {

  public static void main(String[] args) {
    Test test = new Test();

    try {
      System.out.println("Parent try block...");
      try {
        
        test = null;
        System.out.println(test.toString()); // NullPointerException will be thrown
      } catch (NullPointerException npe) {
                
        System.out.println("NullPointerException occurred in nested try-catch block.");
      }
    } catch (Exception e) {
     
      System.out.println("Parent catch block...");
    }
        
  }
}
Output: Parent try block… NullPointerException occurred in nested try-catch block
 
Here, in the nested try-catch block, we have a catch block that catches NullPointerException, so the same was executed.

Example 2:

Missing appropriate nested catch block.

class Test {

  public static void main(String[] args) {
    Test test = new Test();

    try {
      System.out.println("Parent try block...");
      try {
        
        test = null;
        System.out.println(test.toString()); // NullPointerException will be thrown
      } catch (ArithmeticException ae) {
                
        System.out.println("ArithmeticException occurred in nested try-catch block.");
      }
    } catch (Exception e) {
     
      System.out.println("Parent catch block...");
    }
        
  }
}
Output: Parent try block… Parent catch block…
 
In the example above, we did not have a nested catch block written that would catch the NullPointerException, so the parent catch block was executed.
 
We set the parent catch block to catch any exception by specifying the Exception class which is the base class of all exception classes.
 
That’s it!

Leave a Reply

Your email address will not be published.