Flutter dart try catch, catch does not fire

John Gorter picture John Gorter · Jun 28, 2019 · Viewed 73.7k times · Source

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?

Answer

R&#233;mi Rousselet picture Rémi Rousselet · Jun 28, 2019

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.