Curriculum
In Java, you can catch multiple exceptions using a single catch
block. This is useful when you have multiple exceptions that require the same error handling logic. Here’s how you can catch multiple exceptions in Java:
try { // code that may throw an exception } catch (ExceptionType1 | ExceptionType2 | ... | ExceptionTypeN ex) { // error handling logic for ExceptionType1, ExceptionType2, ..., or ExceptionTypeN }
In this syntax, you use the |
symbol to separate multiple exceptions that you want to catch. The exception parameter ex
can be used to reference the caught exception object. Here’s an example:
In this example, we’re using a single catch
block to catch both NullPointerException
and IllegalStateException
. We’re printing the exception message to the console using the getMessage()
method of the caught exception object.
You can catch any number of exceptions using a single catch
block. Here’s another example that shows catching three exceptions using a single catch
block:
In this example, we’re using the |
symbol to separate three exceptions: ExceptionType1
, ExceptionType2
, and ExceptionType3
. All of these exceptions will be caught by the same catch
block.
When catching multiple exceptions, the order of the exceptions is important. You should catch the more specific exceptions first and the more general exceptions later. For example, if you want to catch both IOException
and FileNotFoundException
, you should catch FileNotFoundException
first because it’s a more specific type of IOException
. Here’s an example:
try { // code that may throw an exception } catch (FileNotFoundException ex) { // error handling logic for FileNotFoundException } catch (IOException ex) { // error handling logic for IOException }
In this example, we’re catching FileNotFoundException
first and IOException
second. If an exception is thrown that is a FileNotFoundException
, it will be caught by the first catch
block. If an exception is thrown that is an IOException
but not a FileNotFoundException
, it will be caught by the second catch
block.
In Java, you can catch multiple exceptions using a single catch
block. This is useful when you have multiple exceptions that require the same error handling logic. By understanding the syntax and rules of catching multiple exceptions, you can write more efficient and error-free Java programs.