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?
If a catch block cannot handle the particular exception it has caught, you can rethrow the exception. The rethrow expression ( throw without assignment_expression) causes the originally thrown object to be rethrown.
An exception can be rethrown in a catch block. This action will cause the exception to be passed to the calling method. If the rethrow operation occurs in the main method then the exception is passed to the JVM and displayed on the console.
Catching and throwing exceptions is an overhead and is useless (except if you do something with it before re-throw, i.e. log it), so the programmer will actually be confused, thinking there is a bug and not understanding what the original intent was.
The stack trace contains the Exception's type and a message, and a list of all the method calls which were in progress when it was thrown.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With