如何在Dart中实现异常链接



在Java中,我可以通过将另一个异常传递给新的异常来实现异常链接,如下所示:

try {
doSomething();
} catch (Exception1 ex) {
throw new Exception2("Got exception1 while doing the thing", ex);
}

我想在达特取得类似的成绩。我该怎么做?

这样做的一种方法是:

void main(){
try {
try {
throw 'exception 1';
} catch (e) {
throw LinkedException('exception 2',e);
}
} catch (e) {
throw LinkedException('exception 3',e);
}
}
class LinkedException implements Exception {
final String cause;
final exception;
LinkedException(this.cause,[this.exception]);
@override
String toString() => '$cause <- $exception';
}

如果你捕捉到第三个异常并打印出来,你会得到这样的东西:

exception 3 <- exception 2 <- exception 1

Dartpad跑步示例:https://dartpad.dev/4000ed0f1e170615923f6c1e7f5f468a

最新更新