Combine Exceptions
I have a try and catch inside another catch. I would like to be able to throw back the details of the original exception and the exception that lead to the 2nd exception in the catch.
Can I combine both exceptions into one exception, to pass the details of both? Labeled as 'e3' below.
try
{
;
}
catch ( Exception e1 )
{
try
{
con.rollback();// Rollback Database Changes
}
catch ( Exception e2 )
{
// Combine e1 + e2 into a new Exception, e3
throw e3;
}
throw e1;
}
Thanks.
[1064 byte] By [
pennstumpa] at [2007-10-2 3:52:56]

Thank you, but that doesn't allow you to combine multiple Throwable's. That allows you to combine an existing Throwable into a new one; it doesn't support branching for 2 into 1.Thank you for the thought, though.
That's the only way you can do it. You can always throw Exception or Throwable itself, but that is generally not advisable (especially throwing Throwable in a J2EE application).
You can get the second exception. You simply call getCause() on the exception you receive to obtain a reference to the second exception.
Also, combining exceptions, except as done as above, really does not make sense. You are only allowed by the language to catch and throw a single exception at a time. So, you can either throw an ancestor of both exceptions (ala Exception or Throwable) or 'wrap' one exception inside another and then subsequently retrieve the nested exception (say, for logging).
- Saish
Saisha at 2007-7-15 23:09:20 >

Here's what I put together, does this seem to make sense as a way to combine the stacks from multiple exceptions?
}
catch ( Exception writeException )
{
// Rollback Changes to Database
try
{
con.rollback();
}
catch ( Exception rollbackException )
{
// Combine Exceptions' Stack Traces in 'totalElements'
StackTraceElement[] writeElements = writeException.getStackTrace();
StackTraceElement[] rollbackElements = rollbackException.getStackTrace();
StackTraceElement[] totalElements = new StackTraceElement[ writeElements.length + rollbackElements.length ];
System.arraycopy( rollbackElements, 0, totalElements, 0, rollbackElements.length );
System.arraycopy( writeElements, 0, totalElements, rollbackElements.length, writeElements.length );
// Set Rollback Exception's Complete Stack Trace
rollbackException.setStackTrace( totalElements );
throw rollbackException;
}
}