Catch separate exceptions or use instanceof - Java 6 -


assume piece of code in 20 places , same

try {     // } catch (firstexception e) {     // log } catch (secondexception e) {     // log } 

wouldn't better use or instanceof not solution?

try {     // } catch(exception e) {     logexception(e); }  void logexception(exception e) {     if (e instanceof firstexception) {         // log     } else if (e instanceof secondexception) {         // log differently     } else {         // other exception      } } 

the thing hate solution catching exception definitelly not best way... there better way?

  1. in java 7, use catch (firstexception1 | secondexception | ...)
  2. there may nothing wrong catch (exception e)—you want log all exceptions, don't you? in fact advise catch (throwable t) because outofmemoryerror s , stackoverflowerrors want logged.

an advice many years of experience logging exceptions log them same way. exception message enough human-readable text, , developer needs debugging stack trace.

just careful 1 thing: never catch exceptions early: catch them @ single place whole application, so-called exception barrier—it @ level enter , exit unit of work.

if checked exceptions giving trouble @ lower level, wrap them runtimeexception:

try {   ... }  catch (runtimeexception e) {throw e;}  catch (exception e) {throw new runtimeexception(e);} 

only if know precisely , in advance there exception has business-level meaning application, , not abort current unit of work, redirect flow, appropriate catch exception @ lower level. in practice such exceptions rare compared totality of possible exceptions thrown application code.


Comments