Java / Exception
How do we handle more Than One Type of Exception using catch block in Java?
Using multiple catch blocks we may specify multiples exception to be handled in Java. For example, the below code handles both IOException and SQLException.
catch (IOException ioEx) { logger.log(ioEx); throw ioEx; catch (SQLException sqlEx) { logger.log(sqlEx); throw sqlEx; }
Although the above code handles multiple exceptions, we could notice that both blocks has same code and handling multiple exception sometimes lead to code duplication. Also in releases prior to Java 7, it is difficult to create a common method to eliminate the duplicated code because the exception variable has different types.
In Java SE 7 and later, multiple exception by a single catch block is introduced. This feature eliminates code duplication and reduce the possiblity to catch an overly broad exception.
The following example, which will execute in Java SE 7 and later, eliminates the duplicate code.
catch (IOException|SQLException exception) { logger.log(exception); throw exception; }
The catch clause specifies the types of exceptions that each block can handle, and each exception type is separated with a pipe delimiter (|).
Note that if a catch block handles more than one exception type, then the catch parameter is implicitly final i.e. the exception variable value cannot be changed within the catch block.
More Related questions...