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]
# 1
See the following link and note the second parameter. http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Throwable.html#Throwable(java.lang.String,%20java.lang.Throwable)
jschella at 2007-7-15 23:09:20 > top of Java-index,Developer Tools,Debugging and Profiling Tool APIs...
# 2
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.
pennstumpa at 2007-7-15 23:09:20 > top of Java-index,Developer Tools,Debugging and Profiling Tool APIs...
# 3

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 > top of Java-index,Developer Tools,Debugging and Profiling Tool APIs...
# 4

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;

}

}

pennstumpa at 2007-7-15 23:09:20 > top of Java-index,Developer Tools,Debugging and Profiling Tool APIs...