Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Java catch Multiple Exceptions
Mutliple Catch Blocks



When you're writing Java programs, we know that things don’t always go as expected. Files might be missing, input might be wrong, or something might go wrong with math operations like division. That's where exceptions come in — and Java gives you the power to catch them gracefully. But what if more than one type of exception can happen at the same spot in your code? You don’t need to repeat yourself — you can catch multiple exceptions efficiently.

Why Catch Multiple Exceptions?

Sometimes, a block of code can throw different exceptions. Instead of having separate try-catch blocks for each one, Java allows you to:

Basic Syntax

Separate Catch Blocks

try {
    // code that might throw IOException or ArithmeticException
} catch (IOException e) {
    System.out.println("IO error occurred");
} catch (ArithmeticException e) {
    System.out.println("Arithmetic error occurred");
}

Multi-Catch Block

try {
    // code that might throw IOException or ArithmeticException
} catch (IOException | ArithmeticException e) {
    System.out.println("Exception occurred: " + e.getMessage());
}

Example 1: Separate Catch Blocks

import java.io.*;

public class MultiExceptionDemo1 {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // This will throw ArithmeticException
            FileReader fr = new FileReader("nonexistent.txt"); // This would throw FileNotFoundException
        } catch (ArithmeticException ae) {
            System.out.println("Caught ArithmeticException: " + ae.getMessage());
        } catch (FileNotFoundException fnfe) {
            System.out.println("Caught FileNotFoundException: " + fnfe.getMessage());
        }
    }
}
Caught ArithmeticException: / by zero

Explanation

The division by zero is encountered first, so the ArithmeticException block is executed. The file reading line is never reached due to the earlier exception.

Example 2: Multi-Catch Block

import java.io.*;

public class MultiExceptionDemo2 {
    public static void main(String[] args) {
        try {
            String str = null;
            System.out.println(str.length()); // This will throw NullPointerException
        } catch (IOException | NullPointerException e) {
            System.out.println("Exception caught: " + e.getClass().getSimpleName());
        }
    }
}
Exception caught: NullPointerException

Explanation

Even though IOException was never thrown here, we include it in the multi-catch to show that multiple exceptions can be handled in a single block — provided they are unrelated.

Important Rules of Multi-Catch

What Happens If Exceptions Are Related?

If you try to catch two related exceptions (like IOException and FileNotFoundException) in a multi-catch, Java will throw a compile-time error.

// ❌ This will not compile
try {
    // Some code
} catch (IOException | FileNotFoundException e) {
    // Compile-time error: FileNotFoundException is a subclass of IOException
}

Best Practices

Conclusion

In real-world Java applications, you’ll often deal with multiple types of exceptions. Whether you go for multiple catch blocks or the concise multi-catch syntax, the goal is the same: write clean, readable, and robust code. Java gives you the tools — your job is to use them wisely.

QUIZ

Question 1:What is a valid reason to use a multi-catch block in Java?

Question 2:You can use a multi-catch block to catch exceptions that share a parent-child relationship, like IOException and FileNotFoundException.

Question 3:Which of the following are true about multi-catch blocks in Java?

Question 4:What is the output of the following program?
try {
    int result = 10 / 0;
    FileReader fr = new FileReader("file.txt");
} catch (ArithmeticException ae) {
    System.out.println("Arithmetic error caught");
} catch (FileNotFoundException fnfe) {
    System.out.println("File not found error caught");
}

Question 5:It is possible to use both multi-catch and separate catch blocks in the same try block.

Question 6:Which of the following statements would cause a compile-time error?
try {
    // some risky operations
} catch (IOException | FileNotFoundException e) {
    e.printStackTrace();
}



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M