Easy Tutorial
❮ Java Methods Thread Id ❯

Java Example - Handling Multiple Exceptions (Multiple Catch Blocks)

Java Examples

Handling Exceptions:

  1. When declaring exceptions, it is recommended to declare more specific exceptions, allowing for more specific handling.

  2. For each declared exception, there should be a corresponding catch block. If the exceptions in multiple catch blocks have an inheritance relationship, the parent class exception catch block should be placed at the bottom.

The following example demonstrates how to handle multiple exceptions:

ExceptionDemo.java File

class Demo  
{  
    int div(int a, int b) throws ArithmeticException, ArrayIndexOutOfBoundsException // Declares potential issues with the function using the throws keyword  
    {  
        int[] arr = new int[a];  

        System.out.println(arr[4]); // First exception created  

        return a / b; // Second exception created  
    }  
}  

class ExceptionDemo  
{  
    public static void main(String[] args) // throws Exception  
    {  
        Demo d = new Demo();  

        try  
        {  
            int x = d.div(4, 0); // Three examples in the program run screenshot correspond to these three lines of code  
            // int x = d.div(5, 0);  
            // int x = d.div(4, 1);  
            System.out.println("x=" + x);  
        }  
        catch (ArithmeticException e)  
        {  
            System.out.println(e.toString());  
        }  
        catch (ArrayIndexOutOfBoundsException e)  
        {  
            System.out.println(e.toString());  
        }  
        catch (Exception e) // Parent class, placed here to catch other unexpected exceptions, must be after subclass exception code  
                           // However, it is generally not written  
        {  
            System.out.println(e.toString());  
        }  

        System.out.println("Over");  
    }  
}

The above code outputs the following result:

java.lang.ArrayIndexOutOfBoundsException: 4
Over

Java Examples

❮ Java Methods Thread Id ❯