Search code examples
fluttertry-catchstack-trace

Flutter: keep Stacktrace of an error with try catch


myCrashingFunc() {
  var a = [];
  print(a[0]);
}

try {
  myCrashingFunc()
} catch (e) {
  print(StackTrace.current.toString());
}

Actually, when I debug, I let everything crash so my StackTrace get me to the crashing line.

When I send my app in prod, I use try catch so new errors have default behavior handle.

Problem: with try catch, my Stacktrace stop in the catch, I would like to see the StackTrace give me insigh of the try. (ex: here my StackTrace will only go to the line print(StackTrace.current.toString());

Question: How can I get StackTrace of the function in the try. (ex: hre I would like to see my StackTrace go to line print(a[0]);)


Solution

  • You can access the stacktrace if you pass it as the second argument to catch as follows:

       myCrashingFunc() {
          var a = [];
          print(a[0]);
        }
        
        try {
          myCrashingFunc()
        } on Exception catch (e, s) {
          print(s);
        }