Course contentsShow
← Java
Lesson 761 of 2,87018. Exception Handling FundamentalsFree lesson

Multi-Catch Syntax (Java 7+)

Using the pipe operator to catch multiple exception types in a single catch block.

Multi-Catch Syntax (Java 7+)

What you'll learn: How to handle multiple exception types in a single catch block using Java 7's pipe operator.

The Problem with Repetitive catch Blocks

Before Java 7, if you wanted identical handling for multiple exception types, you had to write separate catch blocks with duplicate code. For example, catching both IOException and SQLException with the same logging logic meant writing nearly identical blocks.

The Multi-Catch Solution

Java 7 introduced multi-catch syntax, allowing you to catch multiple exception types in one catch block using the pipe operator (|):

try {
    // code that may throw exceptions
} catch (IOException | SQLException e) {
    System.out.println("Database or file error: " + e.getMessage());
}

This is cleaner and more maintainable than:

try {
    // code that may throw exceptions
} catch (IOException e) {
    System.out.println("Database or file error: " + e.getMessage());
} catch (SQLException e) {
    System.out.println("Database or file error: " + e.getMessage());
}

Rules and Restrictions

  1. Separate with pipes: Use | between exception types, not commas
  2. Order doesn't matter: Unlike multiple catch blocks, the order of types in a multi-catch doesn't affect compilation
  3. No inheritance relationships: You cannot list a parent and child exception together (e.g., Exception | IOException causes a compiler error because IOException is already covered by Exception)

When to Use Multi-Catch

Use multi-catch when different exception types require identical handling. If exceptions need different responses, use separate catch blocks.

Key Takeaway: Multi-catch syntax (catch (TypeA | TypeB e)) eliminates duplicate exception handling code by letting you catch multiple unrelated exception types in a single block.