81

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)?

IAmYourFaja
  • 55,468
  • 181
  • 466
  • 756

1 Answers1

140
  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.

mskolnick
  • 1,062
  • 8
  • 12
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132