Dart offer

I recently came 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 am wondering which variable e is in the catch clause:

 catch(e) { ... } 

Obviously, this is a kind of exception , but (1) why do not we need to specify its type, and (2) what can I add there to indicate its specific type? For example, how could I handle several types of possible exceptions similarly to catchError(someHandler, test: (e) => e is SomeException) ?

+7
exception-handling try-catch dart
source share
1 answer

1) Dart is an optional typed language. Therefore, type e not required.

2), you should use the following syntax to catch only SomeException :

 try { // ... } on SomeException catch(e) {} 

See the catch section in Dart: Up and Run .

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

+7
source share

All Articles