Multiple Catch Block In Java - Java Tutorial

Multiple Catch Block In Java

BLUF: Mastering Multiple Catch Block In Java is a key requirement for any Java developer. This lesson breaks down the object-oriented principles and syntax required to use this concept in real-world applications.
Write Once, Run Anywhere Tip: Multiple Catch Block In Java

Java's versatility is unmatched. Learn how Multiple Catch Block In Java fits into the Java ecosystem and improves your code structure in the tutorial below.

In Java, utilizing multiple catch blocks enables the distinct handling of various exception types. This approach proves advantageous when a singular try block encompasses code that could potentially throw diverse kinds of exceptions.

Consequently, after a try block, there is an option to include multiple catch blocks, each with a unique exception handler. In situations where different actions need to be taken for various exceptions, the multi-catch block can be employed.

In an alternative approach, it is possible to delineate each exception using the | (pipe) symbol within a unified catch block.

Handling multiple exceptions within a single catch block can help minimize redundancy in the code and enhance its efficiency.

Syntax:

Example

try {  

    //code that may throw exception

} 

catch (Exception1 | Exception2 | Exception3 | Exception4 e) {   

   // Common handling logic for multiple exceptions

}
Example

try {    

                //code that may throw exception

               }    

               catch(Exception1 e1)  {  

                   //handle exception code  

                  }    

               catch(Exception2 e2)   {  

                    //handle exception code  

                  }    

               catch(Exception3 e3)   {  

                    //handle exception code  

                  }        

              catch (Exception e) {

                // Handle any other exceptions (General exception block)

}

Important Points to Remember

  • At a time only one exception occurs and at a time only one catch block is executed.
  • All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.
  • Flowchart of Multi-catch Block

    Examples of Multi Catch Block

Let's examine a straightforward instance of a Java multi-catch block.

Example

Example

public class Main {  

    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");    

    }  

}

Output:

Output

Arithmetic Exception occurs

rest of the code

Example: Handling ArrayIndexOutOfBounds Exception

Example

Example

public class Main {  

    public static void main(String[] args) {  

           try{    

                int a[]=new int[5];    

                System.out.println(a[10]);  

               }    

               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");    

    }  

}

Output:

Output

ArrayIndexOutOfBounds Exception occurs

rest of the code

In this instance, there are two exceptions within the try block. However, only one exception is triggered at a time, leading to the execution of its respective catch block.

Example: Handling ArithmeticException

In this instance, the try block encompasses code that may raise several exceptions, yet solely the initial exception that arises is managed. As 30/0 results in an ArithmeticException, the corresponding catch block is triggered.

Example

Example

public class Main {  

    public static void main(String[] args) {  

           try{    

                int a[]=new int[5];    

                a[5]=30/0;    

                System.out.println(a[10]);  

               }    

               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");    

    }  

}

Output:

Output

Arithmetic Exception occurs

rest of the code

Example: When Any Exception does not Match with Specified Exception

In this instance, a NullPointerException is triggered without specifying the exact exception type. Consequently, the catch block that encompasses the general exception class Exception will be executed.

Example

Example

public class Main {  

    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");    

    }  

}

Output:

Output

Parent Exception occurs

rest of the code

Example: Placing the general Exception catch block before the specific ones

In the provided scenario, the try block has the potential to raise both ArithmeticException and ArrayIndexOutOfBoundsException. It is crucial to note that only one exception is thrown at any given moment, leading to the execution of the catch block that corresponds to that particular exception. If a general Exception catch block is positioned before the specific ones, a compile-time error will arise because the specific catch blocks will be unreachable.

Example

Example

public class Main {    

  public static void main(String args[])

  {    

       try

       {    

            int a[]=new int[5];    

            a[5]=30/0;    

       }    

       catch(Exception e)

       {

           System.out.println("common task completed");

       }    

       catch(ArithmeticException e)

       {

           System.out.println("task1 is completed");

       }    

       catch(ArrayIndexOutOfBoundsException e)

       {

           System.out.println("task 2 completed");

       }    

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

     }    

}

Output:

Output

Main.java:13: error: exception ArithmeticException has already been caught

       catch(ArithmeticException e)

       ^

Main.java:17: error: exception ArrayIndexOutOfBoundsException has already been caught

catch(ArrayIndexOutOfBoundsException e)

Advantages of Multiple Catch Block

  • Specific Exception Handling: By managing each exception type independently, you may provide more accurate error messages and recovery procedures.
  • Code Clarity and Debugging: It facilitates reading and debugging by demonstrating the handling of various errors clearly and concisely.
  • Better Control Flow: This makes it possible for programmers to react differently depending on the kind of exception, resulting in more resilient applications.
  • Avoids Catch-All Logic: This stops the use of a generic catch (Exception e) for anything that could conceal errors or strange behavior.
  • Disadvantages of Multiple Catch Blocks

  • Code Duplication: Repetitive code may result from numerous catch clauses with similar reasoning.
  • Maintenance Overhead: If catch blocks are not arranged correctly, they might become more complex and make maintenance more difficult.
  • Unreachable Code Risk: A compile-time error is brought on by unreachable code when a generic catch block (such as catch(Exception e)) is positioned before a specific one.
  • Longer Code Structure: If too many catch blocks are utilized, the code may become long and less concise.
  • Java Multiple Catch Block MCQs

  1. Select the correct one about multiple catch blocks in Java?
  • They allow handling different types of exceptions in separate blocks.
  • They can only catch exceptions of the same type.
  • They must be nested within each other.
  • They are not supported in Java.

Explanation: Multiple catch blocks allow us to handle different types of exceptions separately. A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler.

  1. What happens if no catch block matches the type of the exception thrown in a try block?
  • The program terminates immediately.
  • The exception is ignored, and the program continues.
  • The exception is propagated up the call stack until it is caught or the program terminates.
  • A default catch block is executed.

Explanation: The following may happen If no catch block matches the type of the exception thrown in a try block.

  • The exception remains unhandled, causing the program to terminate abruptly.
  • Java prints an error message with a stack trace, showing where the exception occurred.
  • No further execution occurs unless the exception is handled by a higher-level exception handler.
  1. Which block must follow a try block?
  • Final
  • Catch
  • Finally
  • None of the above

Explanation: A catch block must follow a try block. It is used to handle the exception that occurs in the try block.

  1. Can you have a finally block after multiple catch blocks?
  • No, a finally block can only be used with a single catch block.
  • A finally block is not allowed in Java.
  • A finally block is only allowed if there are no catch blocks.
  • Yes, a finally block can be placed after multiple catch blocks.

Explanation: Yes, a finally block can be placed after multiple catch blocks. It is optional to place finally block. It is executed even if no catch block execute.

  1. In Java 7 or later versions, what feature allows us to catch multiple exceptions in a single catch block?
  • Nested catch blocks
  • Multi-catch block
  • Exception inheritance
  • Throws keyword

In Java, utilizing multiple catch blocks enables developers to manage distinct types of exceptions individually.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience