To catch several different exceptions that aren't related by inheritance, use multiple catch blocks for a single try - Java Language Basics

Java examples for Language Basics:try catch finally

Description

To catch several different exceptions that aren't related by inheritance, use multiple catch blocks for a single try

try { 
        // code that might generate exceptions 
    } catch  (IOException ioe) { 
        System .out.println ("Input/output error"); 
        System .out.println (ioe.getMessage ()); 
    } catch  (ClassNotFoundException cnfe) { 
        System .out.println ("Class not found"); 
        System .out.println (cnfe.getMessage ()); 
    } catch  (InterruptedException ie) { 
        System .out.println ("Program interrupted"); 
        System .out.println (ie.getMessage ()); 
    } 

Catch more than one class of exceptions in the same catch statement.

The classes must be separated by a pipe character |

try { 
    // code that reads a file from disk 
} catch  (EOFException  | FileNotFoundException exc) { 
    System .out.println ("File error: " + exc.getMessage ()); 
} 

This code catches two exceptions, EOFException and FileNotFoundException, in the same catch block.

The exception is assigned to the exc argument, and its getMessage () method is called.

The exceptions declared as alternatives in the catch statement cannot be superclasses or subclasses of each other unless they are in the proper order.

The following would not work:

try { 
    // code that reads a file from disk 
} catch  (IOException  | EOFException  | FileNotFoundException exc) { 
    System .out.println ("File error: " + exc.getMessage ()); 
} 

The code above has compile error since IOException is the superclass of the other two exceptions and it precedes them in the list.

A superclass can catch exceptions of its subclasses.

The second and third exceptions in that statement never would be caught.

Fixed version:

try { 
    // code that reads a file from disk 
} catch  (EOFException  | FileNotFoundException exc) { 
    System .out.println ("File error: " + exc.getMessage ()); 
} catch  (IOException ioe) { 
    System .out.println ("IO error: " + ioe.getMessage ()); 
} 

Another way to fix it:put the superclass last in the catch statement:

try { 
    // code that reads a file from disk 
} catch  (EOFException  | FileNotFoundException  | IOException exc) { 
    System .out.println ("File error: " + exc.getMessage ()); 
}

Related Tutorials