try with multiple catch block in Java

In Java the way of handling the exceptions varies from exception to exception, hence for every exception type it is highly recommended to use a separate catch block i.e., try with multiple catch blocks.

try with multiple catch block in Java

For Example-

try{
  // Risky code
}
catch(ArithmeticException e)
{
  // Alternative Airthmetic logic
}
catch(FileNotFoundException e)
{
// Alternative logic for fle
}

While working with multiple catch blocks, the order of catch blocks is very important. We have to take the child exception first after that parent exception otherwise we will get compile time error.

For Example- in the below code, we will get compile time error-“Exception ‘java.lang.ArithmeticException’ has already been caught”.

import java.io.FileNotFoundException;

public class ExceptionHandling {
    public static void main(String[] args) {
        try {
            System.out.println(10 / 0);
        }
        catch (Exception e){
            e.printStackTrace();
        }
        catch (ArithmeticException e){
            e.printStackTrace();
        }
    }
}
try with multiple catch block in Java

  • We cannot take more than one catch block for the same exception otherwise we will get compile time error.
import java.io.FileNotFoundException;

public class ExceptionHandling {
    public static void main(String[] args) {
        try {
            System.out.println(10 / 0);
        }
        catch (ArithmeticException e){
            e.printStackTrace();
        }
        catch (ArithmeticException e){
            e.printStackTrace();
        }
    }
}
try with multiple catch block in Java

Similar Java Tutorials

10 thoughts on “try with multiple catch block in Java”

Leave a Comment