异常(Exceptions)
你的Dart
代码可以抛出异常和捕获异常。异常就是出现预期之外的结果的错误。如果没有捕获异常, isolate
将会使异常挂起,往往会导致 isolate
和程序终止。
与java
相反,Dart
中所有异常都是不需检测的异常。方法并不会声明它将抛出哪些异常,而且你不需要去捕捉任何异常。
Dart
除了提供 异常、错误 类型以外还提供了众多预定义的子类型。当然,你可以定义你自己的异常类型。毕竟,Dart
程序可以将任何非空对象作为异常抛出,不只局限与异常和错误对象。
Throw抛出异常
这里抛出了一个异常:
throw FormatException('Expected at least 1 section');
你也可以将任意对象作为异常抛出:
throw 'Out of llamas!';
由于抛出异常是一个表达式,所以可以在 =>
语句中使用,也可以在其他能使用表达式的地方抛出异常。
void distanceTo(Point other) => throw UnimplementedError();
Catch 捕获异常
捕获了一个异常后,就停止了捕获异常过程。捕获一个异常,你就有机会去处理它:
try {
breedMoreLlamas();
} on OutOfLlamasException {
buyMoreLlamas();
}
为了处理含有多种类型异常的代码,你可以选择多个catch
子句。第一个匹配抛出对象类型的catch
子句将会处理这个异常。如果catch
子句未说明所捕获的异常类型,这个子句就可处理任何被抛出的对象。
try {
breedMoreLlamas();
} on OutOfLlamasException {
// A specific exception
buyMoreLlamas();
} on Exception catch (e) {
// Anything else that is an exception
print('Unknown exception: $e');
} catch (e) {
// No specified type, handles all
print('Something really unknown: $e');
}
如之前代码所示,你可以使用on
或者catch
来声明捕获语句,也可以 同时使用。使用on
来指定异常类型,使用catch
来捕获异常对象。
函数 catch()
可以带有一个或者两个参数, 第一个参数为抛出的异常对象, 第二个为堆栈信息 (一个 StackTrace 对象)。
try {
// ···
} on Exception catch (e) {
print('Exception details:\n $e');
} catch (e, s) {
print('Exception details:\n $e');
print('Stack trace:\n $s');
}
使用rethrow
关键字可以把捕获的异常给重新抛出
void misbehave() {
try {
dynamic foo = true;
print(foo++); // Runtime error
} catch (e) {
print('misbehave() partially handled ${e.runtimeType}.');
rethrow; // Allow callers to see the exception.
}
}
void main() {
try {
misbehave();
} catch (e) {
print('main() finished handling ${e.runtimeType}.');
}
}
Finally
为了确保不论是否抛出异常,代码都正常运行,请使用finally
子句。如果没有catch
匹配子句的异常, finally
子句运行以后异常将被传播:
try {
breedMoreLlamas();
} finally {
// Always clean up, even if an exception is thrown.
cleanLlamaStalls();
}
在匹配了所有catch
之后,子句finally
运行了。
try {
breedMoreLlamas();
} catch (e) {
print('Error: $e'); // Handle the exception first.
} finally {
cleanLlamaStalls(); // Then clean up.
}
通过阅读 Exceptions 部分可了解更多。
网友评论