Refactor Exception Handlers

This JavaIdiom allows one to use the same exception handler to handle several exceptions not related by inheritance in any useful way:

  class NonceException? extends Exception{}

try{try{dangerousCode();} catch(FooException? e){throw new NonceException?.initCause(e)));} catch(BarException?? e){throw ((NonceException??)(new NonceException??.initCause(e)));} catch(BazException?? e){throw ((NonceException??)(new NonceException??.initCause(e)));} catch(QuxException?? e){throw ((NonceException??)(new NonceException??.initCause(e)));}} catch(NonceException?? ne) {if(complex_boolean) fail_it(); else ne.getCause().printStackTrace?();}

Now, one can have ONE handler that can access the entire lexical scope, and is close to the text that throws the exception. This uses only the standard facilities supplied by Java, and involves minimal code, useful when you want to create a different NonceException? for each block. Converting this to use a constructor is unnecessary, requires copy-and-paste programming, and will not benefit from any type-safety enhancements that are made to initCause.


CategoryException | CategoryJava
EditText of this page (last edited June 11, 2005)
FindPage by browsing or searching

This page mirrored in JavaIdioms as of April 29, 2006