Technology Encyclopedia Home >How to handle exceptions and errors in Dart?

How to handle exceptions and errors in Dart?

Handling exceptions and errors in Dart involves using try-catch blocks to manage unexpected situations that may occur during the execution of your code. By wrapping code that might throw an exception within a try block, you can catch and handle specific errors in the corresponding catch block.

Basic Syntax

try {
  // Code that might throw an exception
} on TypeOfException catch (e) {
  // Handle the exception of TypeOfException
} catch (e) {
  // Handle other exceptions
} finally {
  // Code that runs regardless of whether an exception occurred
}

Example

Suppose you have a function that divides two numbers:

double divide(int a, int b) {
  try {
    if (b == 0) {
      throw Exception("Division by zero is not allowed.");
    }
    return a / b;
  } catch (e) {
    print("Caught an exception: $e");
    return null;
  }
}

void main() {
  print(divide(10, 2)); // Outputs: 5
  print(divide(10, 0)); // Outputs: Caught an exception: Division by zero is not allowed.
}

Handling Specific Exceptions

You can also handle specific types of exceptions:

try {
  // Code that might throw an exception
} on FormatException catch (e) {
  // Handle FormatException
} on NullPointerException catch (e) {
  // Handle NullPointerException
} catch (e) {
  // Handle other exceptions
}

Using finally

The finally block is optional and contains code that will execute regardless of whether an exception was thrown or not:

try {
  // Code that might throw an exception
} catch (e) {
  // Handle exception
} finally {
  // Code that runs regardless of exceptions
}

Recommended Service for Cloud-Based Applications

For handling exceptions and errors in cloud-based applications, consider using Tencent Cloud's Cloud Log Service. This service allows you to collect, store, and analyze logs from your applications, making it easier to debug and monitor issues in real-time.

By integrating Cloud Log Service with your Dart application, you can log errors and exceptions directly to the cloud, enabling efficient monitoring and troubleshooting.