Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter dart try catch, catch does not fire

Given the shortcode example below:

    ...     print("1 parsing stuff");      List<dynamic> subjectjson;     try {        subjectjson = json.decode(response.body);     } on Exception catch (_) {       print("throwing new error");       throw Exception("Error on server");     }     print("2 parsing stuff");     ... 

I would Expect the catch block to execute whenever the decoding fails. However, when a bad response returns, the terminal displays the exception and neither the catch nor the continuation code fires...

flutter: 1 parsing stuff [VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: type  '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type  'List<dynamic>' 

What am I missing here?

like image 436
John Gorter Avatar asked Jun 28 '19 08:06

John Gorter


People also ask

How do you use try and catch in Dart?

The try / on / catch BlocksThe 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). When an exception occurs in the try block, the control is transferred to the catch.

How do you throw and catch exception in Flutter?

The try block must be followed by on or catch blocks, and an optional finally block. The catch block is used to catch and handle any exceptions thrown in the try block. To catch specific exceptions, the on keyword can be used instead of catch . The catch block can be left at the bottom to catch other exceptions.


2 Answers

Functions can throw anything, even things that aren't an Exception:

void foo() {   throw 42; } 

But the on Exception clause means that you are specifically catching only subclass of Exception.

As such, in the following code:

try {   throw 42; } on Exception catch (_) {   print('never reached'); } 

the on Exception will never be reached.

like image 79
Rémi Rousselet Avatar answered Sep 21 '22 19:09

Rémi Rousselet


It is not a syntax error to have on Exception catch as someone else answered. However you need to be aware that the catch will not be triggered unless the error being thrown is of type Exception.

If you want to find out the exact type of the error you are getting, remove on Exception so that all errors are caught, put a breakpoint within the catch and check the type of the error. You can also use code similar to the following, if you want to do something for Exceptions, and something else for errors of all other types:

try {   ... } on Exception catch (exception) {   ... // only executed if error is of type Exception } catch (error) {   ... // executed for errors of all types other than Exception } 
like image 36
Ovidiu Avatar answered Sep 21 '22 19:09

Ovidiu