Java Catch Multiple Exceptions explained with examples

A catch block is followed by either one or more catch blocks. Each catch block should contain different exception handlers. Java offers different types of catch blocks that handle different types of exceptions. A Multi catch block and a Single catch block are examples of such catch blocks.

Before the publication of Java 7, we needed a unique catch block that could handle a specific exception. Due to this, there was a poor plan of action and extraneous blocks of code. Before learning to catch multiple exceptions, you must be familiar with Java exception handling fundamentals.

Exception handling refers to the effective method for handling runtime problems in Java. This article will enable you to understand the catch of multiple Java exceptions.

Java Multi-catch block

A Java Multi-catch block is used primarily if one has to perform different tasks at the occurrence of various exceptions. One exception co-occurs, and only one catch block is executed. This catch block must have an order from the most specific to the most general. For example, the catch for an arithmetic exception should come before the catch for an exception. When using a multi-catch block, follow the procedure shown below.

The procedure of a multi-catch block

When using a multi-catch block, you first execute the try block. Once this is done, you will have two results, either an exception or no exception. In case you get an exception, go ahead and find an appropriate catch block to execute. In this situation, you can have various exceptions, for instance: executing the catch block for ExceptionType1, executing the catch block for ExceptionType2, executing the catch block for ExceptionTypen, and so on.

Once you complete executing the catch block for any ExceptionType, you execute the statement of a try-catch block. Once this is complete, the program comes to an end. If you executed the try block and got no exception, the statement out of the try-catch block is executed, and the program ends.
Take a look at the code snippets below:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>public class MultipleCatchBlock {   
    public static void main(String[] args) {          
           try{    
                int a[]=new int[7];    
                a[7]=50/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");    
    }  
}</pre>
</div>

The output of the code above is:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>Arithmetic Exception occurs
rest of the code</pre>
</div>

Explanation of the code

In the code above, the two exceptions, ArithmeticException and ArrayIndexOutOfBoundsException, have been handled in the same way. However, two individual catch blocks must be written for them since this is a multi-catch block.

Java Single catch block

This type of block was introduced for Java 7 and beyond. Java allows one to catch multiple type exceptions in a single catch block. This feature has limited the temptation to catch a vast exception. It reduced code duplication hence aiding in the optimization of codes. This feature has also lessened the temptation to catch an overly broad exception.
Consider the code written below, which has duplicate codes in each of the catch blocks:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>public class MultipleExceptionHandling {
	public static void main(String args[]){
		try{    
            int array[] = new int[7];    
            array[7] = 50/0;    
        }    
        catch(ArithmeticException e){  
        	System.out.println("ArithmeticException catch block");
            System.out.println(e.getMessage());  
        }    
        catch(ArrayIndexOutOfBoundsException e){ 
        	System.out.println("ArrayIndexOutOfBoundsException catch block");
            System.out.println(e.getMessage());  
        }    
        catch(Exception e){  
        	System.out.println("Exception catch block");
            System.out.println(e.getMessage());  
        }    
    }
} </pre>
</div>

The output of the code is:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>ArithmeticException catch block
/ by zero</pre>
</div>

In the code above, it is hard to create a common method that can eliminate the duplicated code since the variable e has various types. However, using a single catch block eliminates the duplicated code, as shown below:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>public class MultipleExceptionHandling {
   public static void main(String args[]){
       try{    
            int array[] = new int[7];    
            array[7] = 50/0;    
        }    
        catch(ArithmeticException | ArrayIndexOutOfBoundsException e){  
            System.out.println(e.getMessage());  
        }     
   }
} </pre>
</div>

To separate multiple exceptions in a catch block, you have to use the vertical bar (|) as shown below:
The catch clause is used to specify the type of exceptions that the block can handle.
The exception argument (e) is final, meaning that it cannot be changed, and no other values can be assigned. This feature produces less code repetition and small bytes of code. The syntax of such an exception will be as shown below:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>try {
  // code
} catch (ExceptionType1 | Exceptiontype2 e) { 
  // catch block
}</pre>
</div>

Take a look at the single catch block code snippet below:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>class Main {
  public static void main(String[] args) {
    try {
      int array[] = new int[7];
      array[7] = 50 / 0;
    } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
      System.out.println(e.getMessage());
    }
  }
}</pre>
</div>

The output of the code above is:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>/ by zero </pre>
</div>

In the code above, we have two exceptions for instance:

  1. ArithmeticException, where we are trying to divide an integer by 0. That is, (50 / 0).
  2. ArrayIndexOutOfBoundsException. This exception is because we are trying to assign a value to index 7 while we declare a new integer array with array bounds of 0 to 6, and we are also trying to assign a value to index 7. We use a duplicate code by publishing the message in both catch blocks.

The assignment operator, =, has a right-to-left associativity, so the ArithmeticException is first raised with the message divided by zero.
In the code above, the coding duplication has been decreased, whereas the efficiency has been increased since multiple exceptions have been caught in a single catch block.

Due to the lack of code repetition, the bytecode produced when the program was compiled will be smaller and superior to the bytecode produced when the program could have numerous catch blocks.
The catch parameter is implicitly final when a catch block manages several exceptions. This means we cannot give the catch parameters and values.

Java program to Catch the Base Exception

The rule is generalized to specialized when using a single catch block to catch multiple exceptions. This means that if there is a hierarchy of exceptions in the catch block, we can catch the base exception only instead of catching numerous specialised exceptions. Let us take a look at the code shown below:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>// a Java Program to catch the base exception class only
class Main {
  public static void main(String[] args) {
    try {
      int array[] = new int[7];
      array[7] = 50 / 0;
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
}</pre>
</div>

The output of the code above is:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>/ by zero</pre>
</div>
Explanation of the code

The exception classes in the code above are subclasses of the Exception class. Therefore, we can catch the Exception class instead of catching multiple specialised exceptions.
Let us see an example of handling the exception without maintaining the order of exceptions, from the most specific to the most general.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>class MultipleCatchBlock{    
  public static void main(String args[]){    
   try{    
    int a[]=new int[7];    
    a[7]=50/0;    
   }    
   catch(Exception e){System.out.println("completed common task");}    
   catch(ArithmeticException e){System.out.println("completed task 1");}    
   catch(ArrayIndexOutOfBoundsException e){System.out.println("completed task 2");}    
   System.out.println("rest of the code...");    
 }    
}</pre>
</div>

The output of the code is:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>MultipleCatchBlock.java:8: error: exception ArithmeticException has already been caught
catch(ArithmeticException e){System.out.println("completed task 1");}    
   ^
MultipleCatchBlock.java:9: error: exception ArrayIndexOutOfBoundsException has already been caught
   catch(ArrayIndexOutOfBoundsException e){System.out.println("completed task 2");}  
   ^
2 errors
</pre>
</div>

Java program to catch the base and the child exception classes

In a case where the base exception class has already been specified in the catch block, you should not use the child exception classes in the same catch block. This is because it will result in a complication error. Let us look at the code snippet below:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>// a java program to catch base and child exception class
class Main {
  public static void main(String[] args) {
    try {
      int array[] = new int[7];
      array[7] = 50 / 0;
    } catch (Exception | ArithmeticException | ArrayIndexOutOfBoundsException e) {
      System.out.println(e.getMessage());
    }
  }
}</pre>
</div>

The output of the code is:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>/Main.java:6: error: Alternatives in a multi-catch statement cannot be related by subclassing
} catch (Exception | ArithmeticException | ArrayIndexOutOfBoundsException e) {
                         ^
  Alternative ArithmeticException is a subclass of alternative Exception
Main.java:6: error: Alternatives in a multi-catch statement cannot be related by subclassing
} catch (Exception | ArithmeticException | ArrayIndexOutOfBoundsException e) {
                                               ^
  Alternative ArrayIndexOutOfBoundsException is a subclass of alternative Exception
</pre>
</div>
Explanation of the code

In the code above, we get a compilation error because both ArithmeticException and ArrayIndexOutOfBoundsException are both subclasses of the Exception class.

Let us take another example in Java

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>public class MultipleCatchBlock {  
  
    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");  
                  }    
               catch(ArrayIndexOutOfBoundsException e)  
                  {  
                   System.out.println("ArrayIndexOutOfBounds Exception");  
                  }    
               catch(Exception e)  
                  {  
                   System.out.println("Parent Exception");  
                  }             
               System.out.println("rest of the code");    
    }  
} </pre>
</div>

The output of the code is:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>ArrayIndexOutOfBounds Exception
rest of the code</pre>
</div>
Explanation of the code

There are two exceptions present in the try block in the code above. Only one exception occurs at a time; hence, the associated catch block is performed. The array size in the code is 5, but despite that, we are doing: System.out.println(a[10]); hence, we are getting ArrayIndexOutOfBounds Exception. Let us see what happens if we have multiple errors in the program:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>public class MultipleCatchBlock {  
  
    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");  
                  }    
               catch(ArrayIndexOutOfBoundsException e)  
                  {  
                   System.out.println("ArrayIndexOutOfBounds Exception");  
                  }    
               catch(Exception e)  
                  {  
                   System.out.println("Parent Exception");  
                  }             
               System.out.println("rest of the code");    
    }  
}  </pre>
</div>

The output of the code is:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>Arithmetic Exception
rest of the code</pre>
</div>
Explanation of the code

In the program above, we are not getting the ArrayIndexOutOfBounds Exception even though we were printing a[10] when the array value was 5. This is because the arithmetic exception a[5]=30/0 occurs right before it; hence the catch block catches it and does not execute the code after it in the try block.

Conclusion

This article has illustrated the different catch blocks before and beyond java 7. We have also seen how single and multi-catch exceptions are used. I hope that this article has been of great help to you. Enjoy coding!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *