Justin Fagnani
Justin Fagnani

Reputation: 11171

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

This code:

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

prints:

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?

Upvotes: 42

Views: 27544

Answers (1)

Darshan Rivka Whittle
Darshan Rivka Whittle

Reputation: 34031

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)

Upvotes: 55

Related Questions