Home » Java Multiple Catch Block

Java Multiple Catch Block

Java Multiple Catch Block

Introduction

Java offers a variety of catch blocks to handle different exception types. Before Java 7 was published, we needed a unique catch block to handle a specific exception. As a result, there were extraneous code blocks and a poor plan of action. We can see that a single catch block can handle many exception types as of Java SE 7 and beyond. This feature can limit the temptation to catch an excessively broad exception and reduce code duplication.

In Java, when you’re dealing with code that might throw exceptions, you can enclose that code within a try block. This allows you to manage potential errors gracefully. However, not all exceptions are the same, and sometimes you need to handle different types of exceptions differently.

To achieve this, Java provides the capability to use multiple catch blocks within a single try block. Each catch block is responsible for handling a specific type of exception that might occur within the try block.

Multiple catch blocks in Java are used to catch/handle multiple exceptions  that may be thrown from a particular code section. A try block can have multiple catch blocks to handle multiple exceptions.

Why do we need multiple catch blocks in Java?

Multiple catch blocks in Java are used to handle different types of exceptions. When statements in a single try block generate multiple exceptions, we require multiple catch blocks to handle different types of exceptions. This mechanism is called multi-catch block in java.

A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. You can catch different exceptions in different catch blocks if it contains a different exception handler. When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. So, if you have to perform different tasks at the occurrence of different exceptions, you can use the multi-try catch in Java.

Syntax

try {
   // Protected code
} catch (ExceptionType1 e1) {
   // Catch block
} catch (ExceptionType2 e2) {
   // Catch block
} catch (ExceptionType3 e3) {
   // Catch block
}
Java

Points to Remember while using Multiple Catch Blocks

  • Only one type of exception can be handled at a time. In protected, only one type of exception will be raised, so it will be handled in relevant catch block only.
  • Order of catch block is very important. Order should be from specific exception to generic one. In case of parent exception block comes before the child exception block, compiler will complain and will throw compile time error.

Flow Chart of Java Multiple Catch Block

Example 1.

public class MultipleCatchBlock1 {  
  
    public static void main(String[] args) {  
          
           try{    
                int a[]=new int[5];    
                a[5]=30/0;    
               }    
               catch(ArithmeticException e)  
                  {  
                   System.out.println("Arithmetic Exception occurs");  
                  }    
               catch(ArrayIndexOutOfBoundsException e)  
                  {  
                   System.out.println("ArrayIndexOutOfBounds Exception occurs");  
                  }    
               catch(Exception e)  
                  {  
                   System.out.println("Parent Exception occurs");  
                  }             
               System.out.println("rest of the code");    
    }  
}  
Java

Output

Arithmetic Exception occurs
rest of the code
Java

Example 2.

public class MultipleCatchExample {
    public static void main(String[] args) {
        try {
            // Code that may throw exceptions
            int[] arr = new int[5];
            arr[10] = 10; // This line will throw an ArrayIndexOutOfBoundsException
            int result = 10 / 0; // This line will throw an ArithmeticException
        } catch (ArrayIndexOutOfBoundsException e) {
            // Handle ArrayIndexOutOfBoundsException
            System.out.println("Array index out of bounds!");
        } catch (ArithmeticException e) {
            // Handle ArithmeticException
            System.out.println("Arithmetic error: division by zero!");
        } catch (Exception e) {
            // Handle any other exceptions that are not caught by previous catch blocks
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}
Java

Output

Array index out of bounds!
Java

Example 3.

public class MultipleCatchBlock4 {  
  
    public static void main(String[] args) {  
          
           try{    
                String s=null;  
                System.out.println(s.length());  
               }    
               catch(ArithmeticException e)  
                  {  
                   System.out.println("Arithmetic Exception occurs");  
                  }    
               catch(ArrayIndexOutOfBoundsException e)  
                  {  
                   System.out.println("ArrayIndexOutOfBounds Exception occurs");  
                  }    
               catch(Exception e)  
                  {  
                   System.out.println("Parent Exception occurs");  
                  }             
               System.out.println("rest of the code");    
    }  
}  
Java

Output

Parent Exception occurs
rest of the code
Java

Conclusion

In conclusion, Java’s multiple catch block feature provides a flexible and robust mechanism for handling different types of exceptions gracefully within a single try block. By allowing developers to specify distinct exception types and corresponding handling logic, it enhances code readability, maintainability, and resilience.

Key points to remember about Java’s multiple catch blocks:

  1. Exception Specificity: Each catch block can handle a specific type of exception, allowing for fine-grained error handling tailored to different error scenarios.
  2. Order Matters: catch blocks are evaluated in the order they appear, so it’s crucial to order them from the most specific to the most general exception types. This ensures that more specific exceptions are caught and handled before more general ones.
  3. Comprehensive Error Handling: With multiple catch blocks, it’s possible to provide comprehensive error handling for various types of exceptions that may occur within the same try block.
  4. Graceful Degradation: By catching and handling exceptions gracefully, programs can recover from errors without crashing, providing a smoother user experience and facilitating robust application behavior.

Overall, the multiple catch block feature in Java contributes to the creation of more robust and reliable software systems by enabling developers to manage exceptional conditions effectively.

Frequently Asked Questions

1. Can I have multiple catch blocks for the same exception type?

No, Java does not allow multiple catch blocks for the same exception type within the same try-catch block. If you need to handle the same exception type differently, you can use conditional logic within a single catch block.

2. What happens if an exception is caught by more than one catch block?

Java executes only the first catch block whose exception type matches the thrown exception. It does not evaluate subsequent catch blocks once a match is found.

3. Is it mandatory to have a finally block after multiple catch blocks?

No, the finally block is optional. It’s commonly used for cleanup tasks that should be executed whether or not an exception occurs. If you don’t have any cleanup tasks, you can omit the finally block.