Dart catch clause
Exception HandlingTry CatchDartException 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
-
Dart is an optional typed language. So the type of
e
is not required. -
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.