Multiple Java root causes to an exception

exception, java

Solution

Try:

try {
...
} catch(Exception e) {
  try {
      response.sendError(500);
    } catch(IOException e2) {
      e2.initCause(e);
      throw e2;
    }
}

Problem

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.

Original source