Flutter dart try catch,catch 不开火

Joh*_*ter 34 try-catch catch-block dart flutter

鉴于下面的短代码示例:

    ...
    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");
    ...
Run Code Online (Sandbox Code Playgroud)

我希望在解码失败时执行 catch 块。但是,当返回错误响应时,终端会显示异常,并且不会触发 catch 和继续代码......

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>'
Run Code Online (Sandbox Code Playgroud)

我在这里缺少什么?

Rém*_*let 42

函数可以抛出任何东西,甚至不是Exception

void foo() {
  throw 42;
}
Run Code Online (Sandbox Code Playgroud)

但是on Exception子句的意思是你特别醒目的子类Exception

因此,在以下代码中:

try {
  throw 42;
} on Exception catch (_) {
  print('never reached');
}
Run Code Online (Sandbox Code Playgroud)

on Exception永远不会达到。

  • 啊,你知道的越多⭐ (8认同)
  • @puzzled 它典型的命名参考表明该值永远不会被使用 (4认同)

Ovi*_*diu 35

on Exception catch正如其他人所回答的那样,这不是语法错误。但是,您需要注意,除非抛出的错误类型为 ,否则不会触发捕获Exception

如果你想找出你得到的错误的确切类型,删除on Exception以便捕获所有错误,在 catch 中放置一个断点并检查错误的类型。您还可以使用类似于以下的代码,如果您想为异常做一些事情,并为所有其他类型的错误做一些其他的事情:

try {
  ...
} on Exception catch (exception) {
  ... // only executed if error is of type Exception
} catch (error) {
  ... // executed for errors of all types other than Exception
}
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的回复,使它违反直觉的是错误状态: Unhandled Exception: type .... 所以这使我认为该错误实际上是一个异常,因为我正在捕获基类 Exception,所以我期望catch 要运行..但它没有..所以我猜终端输出显示“未处理的异常”,但该类型实际上根本不是异常:-) (3认同)

小智 10

使用:

try {
  ...
} on Exception catch (exception) {
  ... // only executed if error is of type Exception
} catch (error) {
  ... // executed for errors of all types other than Exception
}
Run Code Online (Sandbox Code Playgroud)


Par*_*iya 8

您示例中的try/catch是同步的,而异常是异步抛出的。如果您将函数标记为异步并在返回之前等待未来,您将按预期捕获异常:

Future<http.Response> foo(url, headers) async {
  try {
    return await http.get(url, headers: headers);
  } catch (e) {
    print(e);
    return null;
  }
}
Run Code Online (Sandbox Code Playgroud)


Moh*_*ami 6

规则是,异常处理应该从详细异常到一般异常,以便使操作落入正确的 catch 块中,并为您提供有关错误的更多信息,例如以下方法中的 catch 块:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*ter 5

    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");
    ...
Run Code Online (Sandbox Code Playgroud)

这确实有效,但这背后的理由是什么?类型不一致不是异常吗?