Flutter and Dart try catch—catch does not fire
Asked Answered
S

8

64

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?

Sudarium answered 28/6, 2019 at 8:43 Comment(3)
is there a reason why you aren't just doing '}catch(_){}'Kamilah
I am doing that now and that works, so I got rid of the on Exception clause.. I was under the assumption that incompatible types where an Exception as well. Should this not work?Sudarium
What is the type that is actually caught? (e.g., do catch (e) { print(e.runtimeType); }). It sounds like a bug if json.decode throws something that isn't an Exception or an Error.Tavis
E
89

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.

Eulaliaeulaliah answered 28/6, 2019 at 8:59 Comment(2)
in catch (_) what is _Phenomenalism
@Phenomenalism Its typical naming reference that dictates that the value will never be usedReputation
A
59

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
}
Anglesey answered 28/6, 2019 at 9:0 Comment(2)
The Exception is the Top in hierarchy for every exceptionArgufy
Thanks for the response, what makes it counter intuitive is that the error states: Unhandled Exception: type .... so this causes me to think that the error actually is an exception and since I am catching on the base class Exception, I expected the catch to run.. but it does not.. So I guess the terminal output says 'unhandled exception' but the type is actually not an exception at all :-)Sudarium
F
10

Use:

try {
  ...
} on Exception catch (exception) {
  ... // only executed if error is of type Exception
} catch (error) {
  ... // executed for errors of all types other than Exception
}
Filigree answered 16/11, 2020 at 12:16 Comment(2)
Please edit your answer to "enter [an] image description [there]". It takes seconds and helps describe what people are in for if they were to click the link.Motorcycle
An explanation would be in order.Macaulay
T
7

The rule is that exception handling should be from detailed exceptions to general exceptions in order to make the operation to fall in the proper catch block and give you more information about the error, like catch blocks in the following method:

Future<int> updateUserById(int userIdForUpdate, String newName) async {
  final db = await database;
  try {
    int code = await db.update('tbl_user', {'name': newName},
        whereArgs: [userIdForUpdate], where: "id = ?");
    return code;
  }
  on DatabaseException catch(de) {
    print(de);
    return 2;
  }
  on FormatException catch(fe) {
    print(fe);
    return 2;
  }
  on Exception catch(e) {
    print(e);
    return 2;
  }
}
Trillbee answered 6/7, 2021 at 7:17 Comment(0)
S
6
    print("1 parsing stuff");
    List<dynamic> subjectjson;
    try {
      subjectjson = json.decode(response.body);
    } catch (_) { .   // <-- removing the on Exception clause
      print("throwing new error");
      throw Exception("Error on server");
    }
    print("2 parsing stuff");
    ...

This works, but what is the rationale behind this? Isn't the type inconsistency an Exception?

Sudarium answered 28/6, 2019 at 8:53 Comment(1)
This is not an answer. Can you move it to the question, please? (But without "Edit:", "Update:", or similar - the question should appear as if it was written today.)Macaulay
C
4

As everybody or most of the people said, try to know exactly what error you are getting:

try{
}
catch(err){
    print(err.runTimeType);
}

runTimeType will give you the type of data or exception you are getting or to put simple the exception itself. And then do whatever you want. (Like if you are not getting the exception of what you expected, then try to fix that issue or change the exception.)

Another option is to go with general form. Using the simple catch which will prompt every time.

Clothier answered 7/5, 2021 at 11:32 Comment(0)
L
3

The other possible reason for the catch bloc not to fire, as pointed out in this question, is missing brackets when throwing an exception.

Must write throw FormatException() instead of throw FormatException.

Latreshia answered 16/8, 2022 at 17:27 Comment(0)
S
0

I had a issue with try catch but my problem was the API that I send http request, doesn't response of my request so that is why my request doesn't response anything and try catch didn't catch the error. So I suggest you to add timeout to your request so that if your api doesn't response your request after a while you can cancel your request with timeout. Here is an example how to use it;

try {
  final response = await http.post(Url).timeout(Duration(seconds: 5));
} catch (error) {
  print(error)
}
Selsyn answered 15/7, 2022 at 8:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.