Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Java root causes to an exception

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.

like image 940
Ryan R. Avatar asked Dec 04 '22 11:12

Ryan R.


2 Answers

Try:

try {
...
} catch(Exception e) {
  try {
      response.sendError(500);
    } catch(IOException e2) {
      e2.initCause(e);
      throw e2;
    }
}
like image 116
ccleve Avatar answered Dec 27 '22 04:12

ccleve


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;
    }
}
like image 28
JustinKSU Avatar answered Dec 27 '22 03:12

JustinKSU