d异常链下个方法

原文

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: 为何!!(t = t.next)不编译?
}

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

这两种情况下都会出现两个链式异常.是否允许用户代码中附加异常?
scope(exit)清理代码中,自动绑定异常.scope(failure)还有点漏洞.

import std.stdio;

void foo() {
  // 漏洞? scope(failure)也应该一样.
  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);
    }
  }
}

//输出:

from foo
from bar

也可用chainTogether.

try {
    foo();

  } catch (Throwable exc) {
    Throwable.chainTogether(exc, new Exception(" ... "));
    throw exc;
  }

准确地说,在"finally"块内抛出异常会链接到前一个异常,但在"catch"块内抛出异常不会.scope(exit)scope(failure)分别只是"finally""catch"的语法糖.
因此,一旦抓到异常,就会结束,之后抛出异常会开始新链.
参考

posted @ 2022-08-15 10:10  zjh6  阅读(16)  评论(0)    收藏  举报  来源