如何重新抛出异常并保留堆栈跟踪?

Jus*_*ani 11 dart

这段代码:

try {
  try {
    throw 1;
  } catch (e, s) {
    print("$e $s");
    throw e;
  }
} catch (e2, s2) {
  print("$e2 $s2");    
}
Run Code Online (Sandbox Code Playgroud)

打印:

1 #0      main (file:///.../test.dart:34:7)

1 #0      main (file:///.../test.dart:37:7)
Run Code Online (Sandbox Code Playgroud)

因此原始堆栈跟踪完全丢失.是否有任何方法可以重新保留堆栈跟踪保留?

Dar*_*tle 14

当前版本的Dart VM并dart2js支持重新抛出,保留堆栈跟踪,具有rethrow:

void main() {
  try {
    try {
      throw 1;
    } catch (e, s) {
      print("$e $s");
      rethrow;
    }
  } catch (e2, s2) {
    print("$e2 $s2");    
  }
}
Run Code Online (Sandbox Code Playgroud)

这会产生:

1 #0      main (file:///home/darshan/so/stacktrace.dart:4:7)

1 #0      main (file:///home/darshan/so/stacktrace.dart:4:7)
#1      main (file:///home/darshan/so/stacktrace.dart:7:7)

  • @Jasper 是的,`throw e;` 是一个普通的 throw,而 `throw;` 是当前写 `rethrow;` 的方式。 (2认同)