Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart catch clause

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

like image 360
IAmYourFaja Avatar asked Dec 27 '13 15:12

IAmYourFaja


People also ask

How do you write a Dart try catch?

The try / on / catch Blocks The on block is used when the exception type needs to be specified. The catch block is used when the handler needs the exception object. The try block must be followed by either exactly one on / catch block or one finally block (or one of both).

How does try catch work in darts?

Dart try-catch is used to execute a block of code that could throw an exception, and handle the exception without letting the program terminate. If an exception, thrown by any of the code, is not handled via catch block, then the program could terminate because of the exception.

What is a catch clause?

In the catch clause, specify the types of exceptions that block can handle, and separate each exception type with a vertical bar ( | ): catch (IOException|SQLException ex) { logger.log(ex); throw ex; } Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final .

How do you catch a specific exception in darts?

You can only specify one type per on xxx catch(e) { line or alternatively use catch(e) to catch all (remaining - see below) exception types. The type after on is used as type for the parameter to catch(e) .


1 Answers

  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.

like image 151
Alexandre Ardhuin Avatar answered Sep 20 '22 16:09

Alexandre Ardhuin