Home » Java » Can I catch multiple Java exceptions in the same catch clause?

Can I catch multiple Java exceptions in the same catch clause?

Posted by: admin November 2, 2017 Leave a comment

Questions:

In Java, I want to do something like this:

try {
    ...     
} catch (IllegalArgumentException, SecurityException, 
       IllegalAccessException, NoSuchFieldException e) {
   someCode();
}

…instead of:

try {
    ...     
} catch (IllegalArgumentException e) {
    someCode();
} catch (SecurityException e) {
    someCode();
} catch (IllegalAccessException e) {
    someCode();
} catch (NoSuchFieldException e) {
    someCode();
}

Is there any way to do this?

Answers:

This is possible since Java 7. The syntax for try-catch block is:

try { 
  ...
} catch (IOException | SQLException ex) { 
  ...
}

Prior to Java 7 this was not possible. Remember though, if all the exceptions belong to the same class hierarchy, you can simply catch that base exception type. The only other way is to catch each exception in its own catch block.

Edit: Note that in Java 7, you cannot catch both ExceptionA and ExceptionB in the same block if ExceptionB is inherited, either directly or indirectly, from ExceptionA. The compiler will complain: The exception ExceptionB is already caught by the alternative ExceptionA.

Questions:
Answers:

Not exactly before Java 7 but, I would do something like this:

Java 6 and before

try {
  //.....
} catch (Exception exc) {
  if (exc instanceof IllegalArgumentException || exc instanceof SecurityException || 
     exc instanceof IllegalAccessException || exc instanceof NoSuchFieldException ) {

     someCode();

  } else if (exc instanceof RuntimeException) {
     throw (RuntimeException) exc;     

  } else {
    throw new RuntimeException(exc);
  }

}

Java 7

try {
  //.....
} catch ( IllegalArgumentException | SecurityException |
         IllegalAccessException |NoSuchFieldException exc) {
  someCode();
}

Questions:
Answers:

Within Java 7 you can define multiple catch clauses like:

catch (IllegalArgumentException | SecurityException e)
{
    ...
}

Questions:
Answers:

No, one per customer.

You can catch a superclass, like java.lang.Exception, as long as you take the same action in all cases.

try {
    // some code
} catch(Exception e) { //All exceptions are caught here as all are inheriting java.lang.Exception
    e.printStackTrace();
}

But that might not be the best practice. You should only catch an exception when you have a strategy for actually handling it – and logging and rethrowing is not “handling it”. If you don’t have a corrective action, better to add it to the method signature and let it bubble up to someone that can handle the situation.

Questions:
Answers:

If there is a hierarchy of exceptions you can use the base class to catch all subclasses of exceptions. In the degenerate case you can catch all Java exceptions with:

try {
   ...
} catch (Exception e) {
   someCode();
}

In a more common case if RepositoryException is the the base class and PathNotFoundException is a derived class then:

try {
   ...
} catch (RepositoryException re) {
   someCode();
} catch (Exception e) {
   someCode();
}

The above code will catch RepositoryException and PathNotFoundException for one kind of exception handling and all other exceptions are lumped together.
Since Java 7, as per @OscarRyz’s answer above:

try { 
  ...
} catch( IOException | SQLException ex ) { 
  ...
}

Questions:
Answers:

A cleaner (but less verbose, and perhaps not as preferred) alternative to user454322’s answer on Java 6 (i.e., Android) would be to catch all Exceptions and re-throw RuntimeExceptions. This wouldn’t work if you’re planning on catching other types of exceptions further up the stack (unless you also re-throw them), but will effectively catch all checked exceptions.

For instance:

try {
    // CODE THAT THROWS EXCEPTION
} catch (Exception e) {
    if (e instanceof RuntimeException) {
        // this exception was not expected, so re-throw it
        throw e;
    } else {
        // YOUR CODE FOR ALL CHECKED EXCEPTIONS
    } 
}

That being said, for verbosity, it might be best to set a boolean or some other variable and based on that execute some code after the try-catch block.

Questions:
Answers:

In pre-7 how about:

  Boolean   caught = true;
  Exception e;
  try {
     ...
     caught = false;
  } catch (TransformerException te) {
     e = te;
  } catch (SocketException se) {
     e = se;
  } catch (IOException ie) {
     e = ie;
  }
  if (caught) {
     someCode(); // You can reference Exception e here.
  }

Questions:
Answers:

yes you can have this in Java 7 see below example

try
{
     //your code
}
catch(SQLException | IOException ex)
{
}

But you need to keep in mind some rules of multi catch, which you can find on below link
http://pictorialjava.blogspot.in/2015/11/exception-handling-in-java-7.html

Questions:
Answers:

Java SE 7 and later multiple catch statements are possible as below..

try{

    //  business logic....

} catch(IOException | SQLException ex){

    // handle exception of both types...

}

Points to mind…

  1. Single catch block can handle more than one type of exception.
  2. Both the exceptions should not be of same type, i.e. you can not catch subclass exception of IOException or SQLException in single catch block.

  3. Catch parameter ex is explicitly final, you can not assign any value to it.

  4. All the exceptions should be separated by vertical bar pipe (|).

Questions:
Answers:

Catch the exception that happens to be a parent class in the exception hierarchy. This is of course, bad practice. In your case, the common parent exception happens to be the Exception class, and catching any exception that is an instance of Exception, is indeed bad practice – exceptions like NullPointerException are usually programming errors and should usually be resolved by checking for null values.

Questions:
Answers:
try {
   ...     
} catch (IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchFieldException e) {
    //even you can check here like 
    if(e instanceof IllegalArgumentException){
       //like wise you can check the type of the exception, its just an info may not required
    }
    someCode();
}

Questions:
Answers:

Yes..You can…

catch(ArithmeticException | ArrayIndexOutOfBounds | RunTimeException | Exception ex) {
ex.printStackTrace();
}

You have to put More Specific Exceptions..i.e Subclasses first and then superclasses…