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

Content added Content deleted
(Fixed and updated D entry)
Line 509: Line 509:


=={{header|D}}==
=={{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.
First exception will be caught and message will be displayed, second will be caught by default exception handler.
<lang d>import std.stdio;
<lang d>class U0 : Exception {
this() @safe pure nothrow { super("U0 error message"); }

class U0 : Exception {
this() nothrow { super("U0 error message"); }
}
}


class U1 : Exception {
class U1 : Exception {
this() nothrow { super("U1 error message"); }
this() @safe pure nothrow { super("U1 error message"); }
}
}


void foo(in int i) pure {
void foo() {
if (i)
import 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 {
try {
bar(i);
i.bar;
} catch (U0 e) {
} catch (U0) {
writeln("Exception U0 caught");
"Function foo caught exception U0".writeln;
}
}
}
}
}

void bar(in int i) @safe pure {
i.baz;
}

void baz(in int i) @safe pure {
throw i ? new U1 : new U0;
}
}


void main() {
void main() {
baz();
foo;
}</lang>
}</lang>
{{output}}
Result:
<pre>test.U1@test.d(8): U1 error message
<pre>test.U1(at)test.d(8): U1 error message
----------------
----------------
\test.d(20): pure void test.bar(int)
\test.d(20): pure void test.bar(int)