How to write try-catch block in Flutter

In Flutter, try-catch blocks are used to handle exceptions that might occur during the execution of a piece of code. When an exception is thrown, the code execution is stopped and the program will jump to the catch block to handle the exception.

Here’s the basic syntax for a try-catch block:

try {
  // Code that might throw an exception
} catch (e) {
  // Code to handle the exception
}

The try block contains the code that might throw an exception. The catch block contains the code to handle the exception. The (e) in the catch block is a variable that represents the exception object.

Here are some examples of how to use try-catch blocks in Flutter:

Catching a specific exception:

try {
  String name = null;
  print(name.length);
} catch (e) {
  if (e is NoSuchMethodError) {
    print('The variable is null!');
  }
}

In this example, we’re trying to get the length of a null string, which will throw a NoSuchMethodError. We catch this specific exception and handle it by printing a message to the console.

Catching multiple exceptions:

try {
  int result = 10 ~/ 0;
  print(result);
} on IntegerDivisionByZeroException catch (e) {
  print('You cannot divide by zero!');
} on FormatException catch (e) {
  print('The input is not valid!');
} catch (e) {
  print('An unknown error occurred!');
}

In this example, we’re trying to divide 10 by 0, which will throw an IntegerDivisionByZeroException. We use the on keyword to catch this specific exception and handle it by printing a message to the console. We also catch a FormatException exception and a generic catch block to handle any other exceptions that might occur.

Rethrowing an exception:

try {
  String name = null;
  print(name.length);
} catch (e) {
  print('An error occurred: $e');
  throw Exception('An error occurred: $e');
}

In this example, we catch the exception and print a message to the console. We then rethrow the exception as a new Exception object with the original exception message. This allows us to handle the exception in a different part of the code, or propagate the error up the call stack.

These are just a few examples of how to use try-catch blocks in Flutter. There are many more options available, such as using the finally block to execute code after the try-catch block regardless of whether an exception was thrown or not. You can find more information on try-catch blocks and exception handling in the Dart language documentation.

Related Posts

Leave a Reply

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