Skip to content

Instantly share code, notes, and snippets.

@developerjamiu
Created May 3, 2022 12:19

Revisions

  1. developerjamiu created this gist May 3, 2022.
    39 changes: 39 additions & 0 deletions error_handling.dart
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    void main() {}

    /// A piece of code checking for errors using exceptions
    /// Checking using exceptions
    void checkingForExceptions() {
    try {
    /// performing operation
    } on FormatException {
    /// Handle exception
    print('Handling format exception');
    } on StateError {
    /// Handle exception
    print('Handling state error');

    /// You can keep adding more chains of On to handle specific errors
    /// Then use catch to catch all other excections
    } catch (ex) {
    print(ex.toString());
    }
    }

    /// Checking using control flow
    void checkingUsingIfElse() {
    // assume
    final bool ifSuccessful = performComplexOperation();

    if (!ifSuccessful) {
    print('An error occured');
    }
    }


    /// Should return true if operation is successful, otherwise return false
    /// We will return false to simulate an error
    bool performComplexOperation() {
    return false;
    }