Java – Handling Multiple Exceptions

Try with Multiple Catch Blocks: One try block can have multiple catch blocks to handle different types of exceptions occur in different lines of code.

Program to read 2 numbers and perform division: In this program, we need to handle two exceptions

InputMismatchException: If the input is invalid
ArithmeticException: If the denominator is zero

Code Program:

import java.util.Scanner;
import java.util.InputMismatchException;
class Code
{
            public static void main(String[] args) {
                        Scanner sc = new Scanner(System.in);
                        try {
                                    System.out.println(“Enter 2 numbers : “);
                                    int a = sc.nextInt();
                                    int b = sc.nextInt();
                                    int c = a/b;
                                    System.out.println(“Sum is : ” + c);
                        }
                        catch (InputMismatchException e1) {
                                    System.out.println(“Exception : Invalid input values”);
                        }
                        catch (ArithmeticException e2) {
                                    System.out.println(“Exception : Denominator should not be zero”);
                        }
            }
}

We can handle Multiple exceptions in following ways:

Try with Multiple Catch blocks: It is useful to provide different message to different exceptions.catch object using Exception class: Same logic to handle all exceptionsUsing Bitwise OR: Related exceptions can handle with single catch block
try
{
}
catch(Exception1 e1)
{
}
catch(Exception2 e2)
{
}  
try
{
} catch(Exception e)
{
}  
try
{
}
catch(Exception1 |  Exception2 e)
{
}  

Exceptions Hierarchy:

  • Throwable is the super class of all exception classes.
  • We can handle only Exceptions in Java not Errors.

Leave a Comment

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

Scroll to Top