Cut single exceptions or use instanceof - Java 6

Suppose this piece of code is in 20 places and always the same

try {
    // do something
} catch (FirstException e) {
    // log it
} catch (SecondException e) {
    // log it
}

Wouldn't it be better to use something like this, or is instanceofnot a good solution?

try {
    // do something
} catch(Exception e) {
    logException(e);
}

void logException(Exception e) {
    if (e instanceof FirstException) {
        // log it
    } else if (e instanceof SecondException) {
        // log it differently
    } else {
        // do something with other exception 
    }
}

The only thing I really hate about the solution is to catch Exception, which is definitely not the best way ... Is there a better way?

+5
source share
4 answers
  • In Java 7 use catch (FirstException1 | SecondException | ...)
  • In catch (Exception e)& mdash could be nothing wrong: you want to log all exceptions, is not it? In fact, I would suggest catch (Throwable t), because OutOfMemoryErrorand StackOverflowErrorshould also be recorded.

, . , , , , , .

: : , - , .

, RuntimeException:

try {
  ...
} 
catch (RuntimeException e) {throw e;} 
catch (Exception e) {throw new RuntimeException(e);}

, , , - , , . , .

+8

. , Exception, RuntimeException.

+1

- , .

.

+1

" " " " - , , instanceof, , .,.

, (w760) ( ).

, - , ? , ., , . :

  • Re-throw., ( )
  • RuntimeException

:

Another thing to keep in mind is that if you need to register these exceptions exactly in the place where they occur, and not spread the chain, and that they occur in 20 different places, then they are a cross-cutting issue. You may have a regular method to simply rearrange the exception and then write an aspect to catch and log., Again using Spring makes this easy.

+1
source

All Articles