Java catch Multiple Exceptions

h‮ptt‬s://www.theitroad.com

In Java, you can catch multiple exceptions using a single catch block. This is useful when you want to handle different types of exceptions in the same way.

The syntax for catching multiple exceptions is as follows:

try {
    // code that may throw an exception
} catch (ExceptionType1 | ExceptionType2 ex) {
    // code to handle exceptions of type ExceptionType1 or ExceptionType2
}

In this syntax, ExceptionType1 and ExceptionType2 are the types of exceptions that you want to catch, separated by the | operator. The exception object is assigned to the variable ex.

Here's an example of catching multiple exceptions:

try {
    // code that may throw an exception
} catch (IOException | ParseException ex) {
    System.out.println("An error occurred: " + ex.getMessage());
}

In this example, the try block contains code that may throw an IOException or a ParseException. The catch block catches both types of exceptions and prints an error message with the exception message.

Note that when catching multiple exceptions, the catch block can only refer to methods or attributes that are common to all the types of exceptions being caught. If you need to access specific methods or attributes of a particular type of exception, you should use separate catch blocks for each type.

try {
    // code that may throw an exception
} catch (IOException ex) {
    System.out.println("An I/O error occurred: " + ex.getMessage());
} catch (ParseException ex) {
    System.out.println("A parse error occurred: " + ex.getMessage());
}

In this example, we have two separate catch blocks, one for IOException and one for ParseException, allowing us to handle each type of exception differently.