How do I rethrow an exception and preserve the stack trace?

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

This produces:

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)

Leave a Comment