How to catch exception in flutter?

In this tutorial, we’ll explore how to catch exception in Flutter and ensure your app can handle unexpected scenarios robustly. In Flutter, as in any programming language, catching exceptions is crucial for building reliable applications. Exception handling allows you to gracefully manage errors and maintain a seamless user experience.

catch exception in flutter

Table of Contents

 

Basic Try-Catch Usage

The most common way to handle exceptions in Flutter is using try-catch blocks. When you wrap your code with a try-catch, you can catch exceptions that may occur during execution. Here’s a simple function and its invocation to illustrate this:

        void processInput(dynamic input) {
            try {
                // Code that may throw an exception
                var result = input / 10;
                print(result);
            } catch (e) {
                print('An error occurred: $e');
            }
        }

        // Call the function
        processInput(100);

Output:

10.0

By catching the exception, we prevent the app from crashing and instead provide a user-friendly error message.

Catching Specific Exceptions

Sometimes you may want to differentiate between exception types and handle each specifically. To do this, you can specify the exception type right after the catch keyword:

        void divideNumbers(int a, int b) {
            try {
                var result = a / b;
                print(result);
            } on IntegerDivisionByZeroException {
                print('Cannot divide by zero.');
            } catch (e) {
                print('An unexpected error occurred: $e');
            }
        }

        // Call the function
        divideNumbers(10, 0);

Output:

Cannot divide by zero.

Creating and Catching Custom Exceptions

You can also define custom exceptions to better represent errors specific to your application’s logic. Here’s how you might define and catch a custom exception:

        class InvalidInputException implements Exception {
            String message;
            InvalidInputException(this.message);
        }

        void validateInput(String input) {
            try {
                if (input.isEmpty) {
                    throw InvalidInputException('Input cannot be empty.');
                }
                print('Input is valid: $input');
            } on InvalidInputException catch (e) {
                print('Validation error: ${e.message}');
            }
        }

        // Call the function
        validateInput('');

Output:

Validation error: Input cannot be empty.

Using the Finally Block

A finally block contains code that should run whether an exception occurs or not. It’s commonly used for cleanup actions, such as closing files or database connections:

        void processResource() {
            try {
                // Code that may throw an exception
            } catch (e) {
                print('An error occurred: $e');
            } finally {
                print('Cleanup actions can be performed here.');
            }
        }

        // Call the function
        processResource();

Output:

Cleanup actions can be performed here.

Handling Exceptions in Asynchronous Operations

When working with asynchronous operations in Flutter, you should use try-catch blocks within async functions and await the potentially failing operation:

        Future<void> fetchData() async {
            try {
                // Simulate a network request
                await Future.delayed(Duration(seconds: 1));
                throw 'Data not found.';
            } catch (e) {
                print('An error occurred: $e');
            }
        }

        // Call the async function
        fetchData();

Output:

An error occurred: Data not found.

Conclusive Summary

Handling exceptions in Flutter is vital for building robust and user-friendly applications. By utilizing try-catch blocks, developers can catch and manage exceptions gracefully. Moreover, using specific exception handling and custom exceptions allows for greater control over error management, improving the overall stability of your apps.

Citations and References

  • The Flutter documentation provides a comprehensive guide on Dart’s error handling mechanisms.
  • Effective Dart: Design – guidelines for exception handling in Dart applications.