Dart
提供了Exception
和Error
以及一些子类型,也支持自定义异常类型。- 有别于
Java
,Dart
异常属于非检查异常。方法不一定声明了所抛出的异常, 也不要求捕获任何异常。 Dart
支持抛出任何非null
对象作为异常,不仅限于实现了Exception
/Error
的对象。catch
中无法指定具体异常类型,需要结合on
来使用。- 使用
rethrow
关键字可以把捕获的异常重新抛出。 finally
关键字的使用和Java
一致。
void f1() {
throw Exception("Juice");
}
void main() {
try {
f1();
} catch (e,s) {
print(e.runtimeType);
print(s.runtimeType);
print(e);
}
}
运行结果为_Exception
_StackTrace
Exception: Juice
区别于java
中的catch
语句catch(Exception e)
,Dart
指明对象的具体类型。e
代表抛出的异常对象,s
表示异常堆栈信息。(命名可以不用e
s