skip to Main Content

I am currently working on a mobile application using Flutter. And I asked myself if it is possible to wrap my entire App in a try/catch and when some Exception occurs that I did not consider while programming show some sort of fatal error screen to the user?

I know that this is probably not considered good practise however I would be happy if some of you would share their opinions on this topic.

I was programmind and asked myself the above mentioned question.

2

Answers


  1. You won’t be able to wrap the entire app in a single try/catch, and that won’t be guaranteed to catch all fatal exceptions that could result in an app crash. While you could wrap all your individual code segments in try/catch blocks, you should ask yourself why this might be helpful.

    Exceptions can provide useful information to the user. If you are making a network call and you get an HttpException, you can inform the user of what happened, and pad their experience in some way. If you get an IOException, they may not have internet connection, etc.

    If the answer to an exception is to lock the user in a generic error screen, you haven’t provided any useful information to the user as to what may have gone wrong, and the only course of action at that point is to restart the application, which would have been faster had it just crashed and re-launched.

    Login or Signup to reply.
  2. Yes, you can. But how to do it depends on the situation. There are three different ways (that I know of).

    1. Synchronous Code

    For an executable of entirely synchronous code, try/catch will suffice:

    void main() {
      try {
        _main();
      }
      catch (error) {
        // do something with error
      }
    }
    
    void _main() {
      ...
    }
    

    2. Asynchronous code

    If your executable uses any asynchronous operations, in order to catch uncaught asynchronous exceptions, you’ll need runZonedGuarded:

    import 'dart:async';
    
    void main() {
      runZonedGuarded(
        () => _main(),
        (error, stackTrace) {
          // do something with error
        }
      );
    }
    
    Future<void> _main() async {
      ...
    }
    

    3. Flutter

    The Flutter framework will use FlutterError.onError for exceptions:

    import 'flutter:widgets.dart';
    
    void main() {
      FlutterError.onError = (FlutterErrorDetails details) {
        // do something with error
      };
      runApp(MyAppWidget());
    }
    

    There are plenty of valid use cases for this, such as instrumenting production applications to track exceptions in the wild.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search