Handling several exceptions in Java

Viewed 1171

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);
} 
8 Answers
Related