How to print exception StackTrace in Dart

Published by admin on

*

Print exception StackTrace in dart :

try-catch block is used to handle exceptions. The catch block can take two parameters : first one is the exception and the second one is a StackTrace object. StackTrace holds the call sequence that triggers one exception. StackTrace is created at runtime and it is an object of class StackTrace.

For example :

main() {
  try {
    throw "Not implemented";
  } catch (e, s) {
    print("Exception $e");
    print("StackTrace $s");
  }
}

It will print the below output :

Exception Not implemented
StackTrace #0      main (file:///Users/cvc/Documents/sample-programs/dart/example.dart:3:5)
#1      _startIsolate.< anonymous closure> (dart:isolate-patch/isolate_patch.dart:305:19)
#2      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)

Dart stacktrace example

As you can see here, the StackTrace contains the file name and the line number. If multiple files are involved in an exception, it will print all these file paths with line numbers.

If you have a production application, you can send the stack trace to crash reporting system to analyse it further.

Categories: dart

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *