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

Fixed and updated D entry
(Fixed and updated D entry)
Line 509:
 
=={{header|D}}==
{{incorrect|D|Function names wrong. foo() <-> baz().}}
First exception will be caught and message will be displayed, second will be caught by default exception handler.
<lang d>importclass std.stdio;U0 : Exception {
this() @safe pure nothrow { super("U0 error message"); }
 
class U0 : Exception {
this() nothrow { super("U0 error message"); }
}
 
class U1 : Exception {
this() @safe pure nothrow { super("U1 error message"); }
}
 
void foo(in int i) pure {
ifimport (i)std.stdio;
throw new U1;
else
throw new U0;
 
foreach (immutable i; 0 .. 2) {
void bar(in int i) pure {
foo(i);
 
void baz() {
foreach (i; 0 .. 2) {
try {
bar(i).bar;
} catch (U0 e) {
writeln("ExceptionFunction U0foo caught exception U0").writeln;
}
}
 
void bar(in int i) @safe pure {
foo(i).baz;
 
void baz(in int i) @safe pure {
throw i ? new throwU1 : new U1U0;
}
 
void main() {
baz()foo;
}</lang>
{{output}}
Result:
<pre>test.U1@(at)test.d(8): U1 error message
----------------
\test.d(20): pure void test.bar(int)