Dart 的错误处理。
Dart 提供了 Exception and Error 两种基础类型来表达错误。它们各自有很多预设的子类型。
抛出一个异常:
throw FormatException("wrong format");箭头(=>)形式的函数,也可以使用 throw 表达式。
void distanceTo(Point other) => throw UnimplementedError();Dart 可以抛出任何类型的异常,但一般来说会抛出 Exception 类或者 Error 类及它们的子类。
处理多种异常:
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 指出处理什么类型的异常(不带 on 时处理所有类型);catch 用来捕捉被 throw 的对象。
捕捉 StackTrace:
try {
// ···
} on Exception catch (e) {
print('Exception details:\n $e');
} catch (e, s) {
print('Exception details:\n $e');
print('Stack trace:\n $s');
}重新抛出异常:
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.
}
}