Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dart

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?

like image 473
Justin Fagnani Avatar asked Apr 16 '13 04:04

Justin Fagnani


People also ask

How do you Rethrow an exception?

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.

What happens when we Rethrow an exception?

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.

Is it good practice to Rethrow exception?

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.

Does exception message contain stack trace?

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.


1 Answers

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) 
like image 82
Darshan Rivka Whittle Avatar answered Oct 14 '22 11:10

Darshan Rivka Whittle