Catching Multiple Exceptions In Java 7

Tech & Media Labs Home RSS Java Exception Handling
  1. Java Exception Handling
  2. Basic try-catch-finally Exception Handling in Java
  3. Java Try With Resources
  4. Catching Multiple Exceptions in Java 7
  5. Exception Hierarchies
  6. Checked or Unchecked Exceptions?
  7. Exception Wrapping
  8. Fail Safe Exception Handling
  9. Pluggable Exception Handlers
  10. Logging Exceptions: Where to Log Exceptions?
  11. Validation - Throw Exceptions Early
  12. Validation - Throw Exception or Return False?
  13. Exception Handling Templates in Java
  14. Exception Enrichment in Java
  15. Execution Context
Catching Multiple Exceptions in Java 7

Jakob Jenkov Last update: 2014-06-23

In Java 7 it was made possible to catch multiple different exceptions in the same catch block. This is also known as multi catch.

Before Java 7 you would write something like this:

try { // execute code that may throw 1 of the 3 exceptions below. } catch(SQLException e) { logger.log(e); } catch(IOException e) { logger.log(e); } catch(Exception e) { logger.severe(e); }

As you can see, the two exceptions SQLException and IOException are handled in the same way, but you still have to write two individual catch blocks for them.

In Java 7 you can catch multiple exceptions using the multi catch syntax:

try { // execute code that may throw 1 of the 3 exceptions below. } catch(SQLException | IOException e) { logger.log(e); } catch(Exception e) { logger.severe(e); }

Notice how the two exception class names in the first catch block are separated by the pipe character |. The pipe character between exception class names is how you declare multiple exceptions to be caught by the same catch clause.

Next: Exception Hierarchies
Tweet

Jakob Jenkov

Featured Videos Java ConcurrentMap + ConcurrentHashMap Java Generics Java ForkJoinPool P2P Networks Introduction Copyright Jenkov Aps Close TOC All Tutorial Trails All Trails Table of contents (TOC) for this tutorial trail Trail TOC Table of contents (TOC) for this tutorial Page TOC Previous tutorial in this tutorial trail Previous Next tutorial in this tutorial trail Next

Tag » How To Catch Multiple Exceptions Java