Suppose i have a method that may fail with a checked exception (checked because it is recoverable, according to Sun’s recommendations).
This method fails and it triggers a recovery strategy.
But both the initial method and the recovery strategy failed.
In some cases i may want to have both stacktraces so that i know why both the initial and recovery strategies failed, and not only the last one.
What can i do?
Should i create a CompositeException type or something like that? Is it a good practice?
Java 7 has introduced the concept of a suppressed exception. For instance, the try-with-resources statement is specified by:
and
This uses java.lang.Throwable.addSuppressedException, whose javadoc reads:
That last paragraph seems to apply to your situation. So you could do:
Then, the stack trace will contain both exceptions:
but only the primary exception can be caught by the caller.