chain of exceptions, next method
Ali Çehreli
acehreli at yahoo.com
Sun Aug 14 02:07:05 UTC 2022
On 8/13/22 15:59, kdevel wrote:
> Quote from `src/druntime/src`:
>
> ```
> /**
> * Returns:
> * A reference to the _next error in the list. This is used when
a new
> * $(D Throwable) is thrown from inside a $(D catch) block. The
> originally
> * caught $(D Exception) will be chained to the new $(D Throwable)
> via this
> * field.
> */
> @property inout(Throwable) next() @safe inout return scope pure
> nothrow @nogc { return nextInChain; }
>
> ```
This automatic "combining" of exceptions happens for cleanup code like
scope(exit). (I remember bug(s) for scope(failure).):
import std.stdio;
void foo() {
// Bug? Should work for scope(failure) as well.
scope (exit) {
bar();
}
throw new Exception("from foo");
}
void bar() {
throw new Exception("from bar");
}
void main() {
try {
foo();
} catch (Exception exc) {
for (Throwable e = exc; e; e = e.next) {
writeln(e.msg);
}
}
}
The output:
from foo
from bar
You can do the same by calling chainTogether(). Here is an excerpt from
an old experiment of mine:
try {
foo();
} catch (Throwable exc) {
Throwable.chainTogether(exc, new Exception(" ... "));
throw exc;
}
Ali
More information about the Digitalmars-d-learn
mailing list