在 flutter 中捕获“as”类型转换异常

Swi*_*ing 4 dart swift flutter

我怎样才能捕获颤动中的“as”类型转换异常。例如,这会导致预期,因为演员阵容不成功。

final success = mapJson['success'] as String;
Run Code Online (Sandbox Code Playgroud)

在 Swift 中我们可以使用guard letorif let语句。flutter/dart 有类似的东西吗?

小智 6

扩展@Christopher的答案,您甚至可以使用on块捕获特定的异常并执行异常特定的代码:

try {

// ...

 } on SomeException catch(e) {

//Handle exception of type SomeException
  print(e)

} catch(e) {

 //Handle all other exceptions
 print(e)

} finally {

  // code that should always execute; irrespective of the exception 
 }
Run Code Online (Sandbox Code Playgroud)