Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling several exceptions in Java

Consider the following Java code:

try{

    // do something
    // this piece of code throws several checked exceptions.

} catch (IllegalArgumentException e) {
    handleException(e);
} catch (IllegalAccessException e) {
    handleException(e);
} catch (InvocationTargetException e) {
    handleException(e);
} catch (InstantiationException e) {
    handleException(e);
} catch (NoSuchMethodException e) {
    handleException(e);
} catch (IOException e) {
    handleException(e);
} catch (NoSuchFieldException e) {
    handleException(e);
}

The code in try block throws several checked exceptions. All I want to do is to log a message when an exception occurs (with some custom message strings). I.e. my exception handling logic is same for all exceptions.

I feel the above code dosn't look good (more LOC and reduced readability).

Is there any better ways to handle such cases?

The following solution is not a best practice, so not recommended (by Check style).

try{
    // do something very bad
} catch (Exception e) {
    handleException(e);
} 
like image 542
Veera Avatar asked Jul 16 '12 18:07

Veera


People also ask

Can you have multiple exceptions in Java?

Java allows you to catch multiple type exceptions in a single catch block. It was introduced in Java 7 and helps to optimize code. You can use vertical bar (|) to separate multiple exceptions in catch block.

How do you handle multiple exceptions in a single catch?

If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can't change it. The byte code generated by this feature is smaller and reduce code redundancy.


1 Answers

In Java 6 you don't have any option much more appealing than what you have already suggested.

But Java 7 has a multi-catch statement that you can use:

catch(IllegalArgumentException | IllegalAccessException | IOException exception) {
    handleException(e);
}
like image 59
Mark Byers Avatar answered Oct 29 '22 05:10

Mark Byers