I have an interesting scenario where I am setting an HttpServletResponse error in a catch clause. The "response.sendError(..)" also throws an exception. What is the best way to deal with exceptions during exception handling to preserve the original exception detail?
I have something like this:
try {
...
} catch(Exception e) {
try {
response.sendError(500);
} catch(IOException e2) {
//Can I do something like:
//'throw new ServletException(e,e2)' here?
}
}
In other words, what is the best way to bundle up the information from both exceptions into the next exception thrown? I don't want to lose the information from the first exception when handling the second.
In general, multiple try catch blocks seem horrible for readability. Would ideally like to avoid that mess. Could always bundle up the embedded try/catch in a method... still seems bad though and doesn't resolve keeping all the exception detail.
Try:
try {
...
} catch(Exception e) {
try {
response.sendError(500);
} catch(IOException e2) {
e2.initCause(e);
throw e2;
}
}
Using initCause()
will not aways work if the exception already has a cause. Instead you can use addSupressed()
to include the an exception in a different exceptions's stack trace.
try {
...
} catch(Exception e) {
try {
response.sendError(500);
} catch(IOException e2) {
e.addSuppressed(e2);
throw e;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With