Dart catch clause

Exception HandlingTry CatchDart

Exception Handling Problem Overview


I recently stumbled across the following Dart code:

void doSomething(String url, String method) {
    HttpRequest request = new HttpRequest();

    request.open(method, url);
    request.onLoad.listen((event) {
        if(request.status < 400) {
            try {
                String json = request.responseText;
            } catch(e) {
                print("Error!");
            }
        } else {
            print("Error! (400+)");
        }
    });

    request.setRequestHeader("Accept", ApplicationJSON);
}

I'm wondering what the e variable is in the catch clause:

catch(e) {
    ...
}

Obviously its some sort of exception, but (1) why do we not need to specify its type, and (2) what could I add in there to specify its concrete type? For instance, how could I handle multiple types of possible exceptions in a similar way to catchError(someHandler, test: (e) => e is SomeException)?

Exception Handling Solutions


Solution 1 - Exception Handling

  1. Dart is an optional typed language. So the type of e is not required.

  2. you have to use the following syntax to catch only SomeException :

try {
  // ...
} on SomeException catch(e) {
 //Handle exception of type SomeException
} catch(e) {
 //Handle all other exceptions
}

See catch section of Dart: Up and Running.

Finally catch can accept 2 parameters ( catch(e, s) ) where the second parameter is the StackTrace.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIAmYourFajaView Question on Stackoverflow
Solution 1 - Exception HandlingAlexandre ArdhuinView Answer on Stackoverflow