Intercept and rethrow a Java unhandled exception -
i've coded method catch-all handler, need rethrow exception if unhandled, caller (much) further call stack can handle it. trivial way simply:
try { ... } catch (exception ex) { // here... // , rethrow throw ex; }
but problem that, because of throw
statement, java requires method declare throws exception
, in turn, requires callers handle exception or declare throws exception
. , on call chain...
is there simple way rethrow exception if current method did not handle it?
you @radoh has said , wrap runtimeexception
, 1 downside of stacktrace polluted , show offending line declare throw new runtimeexception(ex)
.
an alternative use lomboks sneakythrows
mechanism, this:
public static void main(string[] args) { methodwithexception(); } private static void methodwithexception() { try { throw new exception("hello"); } catch (exception e) { lombok.sneakythrow(e); } }
your stacktrace remain intact, no longer need declare throws exception
.
it's worth reading documentation on why should/shouldn't this
Comments
Post a Comment