Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Multiple catch Clauses

If single try statement generates two or more type of exception, it is not possible to handle different types of exceptions by a single catch clause, unless & until it uses a superclass type for all the exceptions generated in a try block.

To handle different type of exceptions it is good to use multiple catch clauses.

For better understanding, consider an example given below:

Example

import java.util.Scanner;

class MultiExcpDemo 
{
    public static void main(String args[]) 
    {
        System.out.println("Enter any number :: ");
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        in.close();
        
        try
        {
            int i = 10/num;
            System.out.println("i = "+i);
            String str = null;
            System.out.println(str.length());
        }
        catch(ArithmeticException e)
        {
            System.out.println("Arithmetic Exception Handled");
        }			
    }
}

In the above program, line

 int i = 10/num;

will throw AritmeticException if num is equal to zero.

And line

System.out.println(str.length());

will throw NullPointerException if num is not equal to zero.

If try block generates ArithmeticException, then it will be caught easily by catch clause because catch clause is capable of catching ArithmeticException.

But if try block generates NullPointerException, then it is not possible for catch clause to catch it because catch clause is capable of catching ArithmeticException only, not NullPointerException.

Now there is another way to handle this type of situation, by using single catch block. By using class Exception type (superclass of all exception types) in the catch clause, it is possible to handle all type of exceptions generated in a try block.

Example

import java.util.Scanner;

class MultiExcpDemo2 
{
    public static void main(String args[]) 
    {
        System.out.println("Enter any number :: ");
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        in.close();
        
        try
        {
            int i = 10/num;
            System.out.println("i = "+i);
            String str = null;
            System.out.println(str.length());
        }
        catch(Exception e)
        {
            System.out.println("Exception Handled");
        }			
    }
}

Now catch clause using Exception type can handle all type of exceptions thrown by try block. But this is not a good programming because this does not make us know the exact reason of exception occurrence.

Therefore Java has provided another way to handle different type of exceptions thrown by single try block using multiple catch clauses.

import java.util.Scanner;

class MultiExcpDemo3 
{
    public static void main(String args[]) 
    {
        System.out.println("Enter any number :: ");
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        in.close();
        
        try
        {
            int i = 10/num;
            System.out.println("i = "+i);
            String str = null;
            System.out.println(str.length());
        }
        catch(ArithmeticException e)
        {
            System.out.println("Arithmetic Exception Handled");
        }
        catch(NullPointerException e)
        {
            System.out.println("Null Pointer Exception Handled");
        }
    }
}

In the above program if user enters zero then try block will throw ArithmeticException at line

 int i = 10/num;

& will be caught directly by catch clause containing ArithmeticException handling mechanism.

But the rest of the code after line

int i = 10/num;

will be skipped.

Example

Enter any number ::
0
Arithmetic Exception Handled

If user enters integer value other than zero, then try block will throw NullPointerException at line,

System.out.println(str.length());

& will be caught directly by catch clause containing NullPointerException handling mechanism.

But the rest of code after line (if available)

System.out.println(str.length());

will be skipped.

Example

Enter any number ::
5
Null Pointer Exception Handled

Thus from the above program, we can conclude that we can use single try block with multiple catch clauses to handle different type of exceptions.

What must care to be taken while using multiple catch clauses?

While using multiple catch clauses with a single try block, we must take care that superclass of exceptions must not come before its subclass type because if superclass of exceptions is used first, it will handle all the exceptions of its type as well as of its all subclasses. Thus catch clauses containing exception subclasses will never be able to catch exceptions.

Therefore Java gives a compile time error if any superclass is used before its subclasses in multiple catch clauses.

Example

import java.util.Scanner;

class SuperclassFirst 
{
    public static void main(String args[]) 
    {
        System.out.println("Enter any number :: ");
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        in.close();
        
        try
        {
            int i = 10/num;
            System.out.println("i = "+i);
            String str = null;
            System.out.println(str.length());
        }
        catch(Exception e)
        {
            System.out.println("Exception Handled");
        }
        catch(ArithmeticException e)
        {
            System.out.println("Arithmetic Exception Handled");
        }
        catch(NullPointerException e)
        {
            System.out.println("Null Pointer Exception Handled");
        } 
    }
}

If we try to compile this program, we’ll get compile time error

Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception
Unreachable catch block for NullPointerException. It is already handled by the catch block for Exception

Compile time error has occurred because Exception class is a superclass of the classes ArithmeticException & NullPointerException.

If Exception class is used before its subclasses, ArithmeticException & NullPointerException would never be able to catch any exception of their type.

Therefore any superclass should not be used before its subclasses.

For better understanding, look at the diagram given below:

All the balls with different sizes are considered as different types of exceptions. And all the pots are considered as different types of classes that can handle/catch exceptions occurred.

The large pot is considered as a superclass of other two pots.

Medium size pot is considered as a subclass of the large pot & superclass of the small pot.

The small pot is considered as a subclass of large & medium size pots.

If large pot (superclass) is placed before other pots, it will catch all types of balls (exceptions) therefore no any ball will reach to other pots. Then what’s the use other small pots if they are never reached by balls?

Therefore it is considered as a very wrong way/order to arrange the pots.

Similarly, Java considers wrong of using superclass before subclass to catch exceptions.

The arrangement of pots should be in the reversed order.

Java Programming Language Multiple catch Clauses Example 1

The correct way is that the superclass type must come at last of all its subclasses, as shown below:

Example

import java.util.Scanner;
 
class SuperclassLast  
{
    public static void main(String args[]) 
    {
        System.out.println("Enter any number :: ");
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        in.close();
        
        try
        {
            int i = 10/num;
            System.out.println("i = "+i);
            String str = null;
            System.out.println(str.length());
        }
        catch(ArithmeticException e)
        {
            System.out.println("Arithmetic Exception Handled");
        }
        catch(NullPointerException e)
        {
            System.out.println("Null Pointer Exception Handled");
        }
        catch(Exception e)
        {
            System.out.println("Exception Handled");
        }
    }
}

Java Programming Language Multiple catch Clauses Example 2

Leave a reply