如何抛出异常并保留堆栈跟踪? [英] How do I rethrow an exception and preserve the stack trace?

查看:94
本文介绍了如何抛出异常并保留堆栈跟踪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

try {
  try {
    throw 1;
  } catch (e, s) {
    print("$e $s");
    throw e;
  }
} catch (e2, s2) {
  print("$e2 $s2");    
}

打印:

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

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

因此原始堆栈跟踪信息完全丢失。有什么办法可以保留堆栈跟踪吗?

So the original stack trace is completely lost. Is there any way to rethrow with the stack trace preserved?

推荐答案

Dart VM的当前版本和 dart2js 通过 rethrow 支持重新抛出,保留堆栈跟踪:

Current versions of the Dart VM and dart2js support rethrowing, preserving the stack trace, with rethrow:

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

这将产生:


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)

这篇关于如何抛出异常并保留堆栈跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆