乐闻世界logo
搜索文章和话题

How to Handle Exceptions in Dart?

2月7日 11:31

In Dart, exception handling primarily relies on the keywords try, catch, and finally. The following are the basic steps for handling exceptions:

  1. Use the try block: Place code that may throw exceptions within a try block.

  2. Catch exceptions:

    • Use the catch block to catch exceptions. You can specify one or more catch blocks to handle different types of exceptions.
    • The catch block can receive an exception object, typically named e, and optionally a stack trace object, typically named s.

    Example:

    dart
    try { // Code that may throw an exception } catch (e) { // Handle the exception print('Exception: $e'); }

    Or more detailed catching:

    dart
    try { // Code that may throw an exception } on SpecificException catch (e) { // Handle specific exception print('Specific exception: $e'); } catch (e, s) { // Handle all other exceptions and print stack trace print('Exception: $e'); print('Stack trace: $s'); }
  3. Use the finally block: The code within the finally block is executed regardless of whether an exception occurred. This is commonly used for resource cleanup, such as closing files or database connections.

    Example:

    dart
    try { // Code that may throw an exception } catch (e) { // Handle the exception print('Exception: $e'); } finally { // Cleanup code that is always executed print('This is the finally block, executed regardless of exceptions.'); }

Through these mechanisms, you can effectively handle errors and exceptions that may occur during code execution, ensuring the stability and reliability of the program.

标签:Dart