Observing exceptions in a destructor

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 21 19:55:47 PDT 2015


On Wednesday, April 22, 2015 01:02:15 Mark Isaacson via Digitalmars-d-learn wrote:
> I'd like to be able to know if my destructor is being called
> because an exception was thrown. Any way to do that?
>
> I tried this: http://ideone.com/JbXH2w
>
> (Pasted here for convenience):
>
> import std.stdio, std.exception;
>
> struct Catcher {
>   ~this() {
>       try {} catch (Exception e) {
>           writeln("Woooo!");
>           throw e;
>       }
>       scope (failure) {
>           writeln("Woooo woooo!");
>       }
>       writeln("Destructing...");
>   }
> }
>
> void main() {
>   scope (failure) writeln("Sensible");
>   scope (exit) writeln("Always written");
>   Catcher c1;
>   scope auto c2 = Catcher();
>   throw new Exception("Foobar");
> }
>
> Which does not print the "Wooo" lines, but does print all the
> others.

The exception isn't being thrown in the destructor, so there's no exception
to catch. It's more like

catch(Exception e)
{
    call_destructor_on_c1();
    throw e;
}

AFAIK, there is no way to detect whether a destructor is being called
because of an exception being thrown.

Why would you need to know anyway? Just for debugging purposes? I can't
think of any case where it would matter.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list