使用一个catch表达式在Dart中捕获多种特定的异常类型

Fel*_*ütz 8 exception try-catch dart

我知道我可以使用以下命令在dart中捕获特定的Exception类型:

try {
  ...
} on SpecificException catch(e) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

但是,有没有一种方法可以在线捕获多个特定的异常类型,而不是使用多个catch语句?

Moa*_*idt 16

不,没有,但你可以这样做:

try {
  ...
} catch (e) {
  if (e is A || e is B) {
    ...
  } else {
    rethrow;
  }
}
Run Code Online (Sandbox Code Playgroud)


Gün*_*uer 7

您只能在每on xxx catch(e) {行中指定一种类型,也可以 catch(e)用于捕获所有(其余-参见下文)异常类型。之后的on类型用作的参数类型catch(e)。为该参数设置一组类型效果不佳。

try {
  ...
} on A catch(e) {
  ...
} on B catch(e) {
  ...
} catch(e) { // everything else
}
Run Code Online (Sandbox Code Playgroud)