The Proper Use of Exception Chaining: Caught between two conflicting usecases?
FeepingCreature
feepingcreature at gmail.com
Tue Apr 9 14:27:37 UTC 2019
There's a feature where, when creating an exception, you can pass
another exception as a second parameter. I always thought that
the point of this feature was that you could get a backtrace like:
void foo() {
throw new FooException("foo failure");
}
void bar() {
try foo;
catch (FooException fooException) {
throw new BarException("bar failure", fooException);
}
}
-----------
FooException: foo failure
main.d: foo()
BarException: bar failure
main.d: bar()
main.d: main()
But it turns out that according to the runtime it's related to
throwing exceptions as a side effect of unwinding? Ie. if you
scope(exit) throw new BarException("bar");
throw new FooException("foo");
then you get a BarException chained to the FooException? Or the
other way around?
That seems a **very** different usecase from the original one.
In the second case, while processing an error we coincidentally
encountered a second error.
In the first case, it's still the same error, just being
represented now by a different class.
Furthermore, the runtime seems to think case 2 is the correct use
for chained exceptions, whereas the documentation (
https://dlang.org/library/object/throwable.next.html ),
admittedly a bit hidden away, claims that case 1 is the proper
usecase.
In any case, Throwable.toString doesn't care and just omits the
chained exception outright.
This seems a very unsatisfying state of affairs! If the use of
exception chaining on throwing an exception during unwind cannot
be changed, then there is still a case for creating a whole
separate implementation of chaining ("exception wrapping"?) for
case 2, and reinterpreting the rarely used two-parameter syntax
(new Exception("bla", wrapped)) to use this idiom, as well as
prominently displaying the wrapped exception in toString output.
I'm very willing to work out a PR for this, but I want to avoid
the effort if it's unlikely to be accepted.
What do you think?
More information about the Digitalmars-d
mailing list