Skip to content

Instantly share code, notes, and snippets.

@iAmWillShepherd
Created December 8, 2021 16:39
Show Gist options
  • Save iAmWillShepherd/89b9153f435db06b1349d7898a4a06dc to your computer and use it in GitHub Desktop.
Save iAmWillShepherd/89b9153f435db06b1349d7898a4a06dc to your computer and use it in GitHub Desktop.
Dart allows you to throw any object and get a stacktrace

You can throw any valid object in Dart and still get a stack trace. Note that the stacktrace is independent from the error/exception.

Throwing a string

void main(List<String> arguments) {
  try {
    throw "I'm throwing a string, not an error!";
  } catch (e, stack) {
    print(
      "error: $e",
    );

    print("stack: $stack");
  }
}
Output
╭─iamwill@zues ~/Desktop/test 
╰─$ dart run                                                           255 ↵
error: I'm throwing a string, not an error!
stack: #0      main (file:///Users/iamwill/Desktop/test/bin/test.dart:3:5)
#1      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:281:32)
#2      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)

Throwing a boolean

void main(List<String> arguments) {
  try {
    throw false;
  } catch (e, stack) {
    print(
      "error: $e",
    );

    print("stack: $stack");
  }
}
Output
╭─iamwill@zues ~/Desktop/test 
╰─$ dart run
error: false
stack: #0      main (file:///Users/iamwill/Desktop/test/bin/test.dart:3:5)
#1      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:281:32)
#2      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)

Throwing a number

void main(List<String> arguments) {
  try {
    throw 8;
  } catch (e, stack) {
    print(
      "error: $e",
    );

    print("stack: $stack");
  }
}
Output
╭─iamwill@zues ~/Desktop/test 
╰─$ dart run
error: 8
stack: #0      main (file:///Users/iamwill/Desktop/test/bin/test.dart:3:5)
#1      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:281:32)
#2      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment