Exceptions/Catch an exception thrown in a nested call: Difference between revisions

added C++ implementation
(→‎{{header|Ada}}: Explanation of unhandled exceptions added)
(added C++ implementation)
Line 48:
An unhandled exception leads to termination of the corresponding [[task]]. When the task is the main task of the program as in the example, the whole program is terminated. In the example the exception back tracing message is compiler-specific (in this case it is [[GNAT]] and further depends on the compiler options.
 
=={{header|C++}}==
First exception will be caught and message will be displayed, second will be caught by the default exception handler, which as required by the C++ Standard, will call terminate(), aborting the task,
typically with an error message.
 
<lang C++>
#include <iostream>
class U0 {};
class U1 {};
void baz(int i)
{
if (!i) throw U0();
else throw U1();
}
void bar(int i) { baz(i); }
void foo()
{
for (int i = 0; i < 2; i++)
{
try {
bar(i);
} catch(U0 e) {
std::cout<< "Exception U0 caught\n";
}
}
}
int main() {
foo();
std::cout<< "Should never get here!\n";
return 0;
}
</lang>
 
Result:
<pre>
Exception U0 caught
This application has requested the Runtime to terminate it in an unusual way.
</pre>
The exact behavior for an uncaught exception is implementation-defined.
=={{header|D}}==
First exception will be caught and message will be displayed, second will be caught by default exception handler.
3

edits