Throwing a new exception while throwing an old exception

c++, exception, java

Solution

Think in terms of flow control. Exceptions are fundamentally just fancy `setjmp`/`longjmp` or `setcc`/`callcc` anyway. The exception object is used to select a particular place to jump to, like an address. The exception handler simply recurses on the current exception, `longjmp`ing until it is handled.

Handling two exceptions at a time is simply a matter of bundling them together into one, such that the result produces coherent flow control. I can think of two alternatives:

- Combine them into an uncatchable exception. It would amount to unwinding the entire stack and ignoring all handlers. This creates the risk of an exception cascade causing totally random behavior.

- Somehow construct their Cartesian product. Yeah, right.

The C++ methodology serves the interest of predictability well.

Problem

If a destructor throws in C++ during stack unwinding caused by an exception, the program terminates. (That's why destructors should never throw in C++.) Example: ``` struct Foo { ~Foo() { throw 2; // whoops, already throwing 1 at this point, let's terminate! } }; int main() { Foo foo; throw 1; } terminate called after throwing an instance of 'int' This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. ``` If a finally block is entered in Java because of an exception in the corresponding try block and that finally block throws a second exception, the first exception is silently swallowed. Example: ``` public static void foo() throws Exception { try { throw new Exception("first"); } finally { throw new Exception("second"); } } public static void main(String[] args) { try { foo(); } catch (Exception e) { System.out.println(e.getMessage()); // prints "second" } } ``` This question crossed my mind: Could a programming language handle multiple exceptions being thrown at the same time? Would that be useful? Have you ever missed that ability? Is there a language that already supports this? Is there any experience with such an approach? Any thoughts?

Original source