chain of exceptions, next method

kdevel kdevel at vogtner.de
Sat Aug 13 22:59:16 UTC 2022


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; }

```

Testcode:

```
import std.stdio;
import std.exception;

private:

class E1 : Exception { mixin basicExceptionCtors; }
class E2 : Exception { mixin basicExceptionCtors; }

void foo ()
{
    try throw new E1 ("e1");
    catch (Exception e)
       throw new E2 ("e2");
}

void bar ()
{
    auto e = new E1 ("e1");
    e.next = new E2 ("e2");
    throw e;
}

void dumpall (Exception e)
{
    Throwable t = e;
    stderr.writeln ("dumpall");
    do
       stderr.writeln (t.msg);
    while ((t = t.next) !is null); // XXX: Why does !!(t = t.next) 
not compile?
}

public void main ()
{
    try foo ();
    catch (Exception e)
       dumpall (e);

    try bar ();
    catch (Exception e)
       dumpall (e);
}

$ dmd cetest
$ ./cetest
dumpall
e2
dumpall
e1
e2
```

Would have expected two chained Exceptions in both cases. Is it 
permitted to append exceptions from user code?



More information about the Digitalmars-d-learn mailing list