6.Exceptions-异常(Dart中文文档)

时间:2023-03-09 13:02:24
6.Exceptions-异常(Dart中文文档)

异常是用于标识程序发生未知异常。如果异常没有被捕获,If the exception isn’t caught, the isolate that raised the exception is suspended, and typically the isolate and its program are terminated.

对比java,Dart的异常都是未检查异常,方法不需要定义要抛出的异常类型,调用时也没有要求捕获异常。

Dart提供了Exception和Error的异常类,你也可以定义自己的异常。同时,Dart的异常抛出,不仅仅只能是继承至Exception或者Error的类,任意类对象都可以作为异常抛出。

Throw

throw FormatException('Expected at least 1 section');

你也可以抛出任意对象

throw 'Out of llamas!';

注意:虽然异常可以抛出任意对象,但是一般来说还是要抛出继承于Error或者Exception的对象

因为throw an exception是一个表达式,所以它可以在箭头函数的简化写法。

void distanceTo(Point other) => throw UnimplementedError();

Catch

捕获异常可以终止异常的传递(除非你重新抛异常)。

try {
breedMoreLlamas();
} on OutOfLlamasException {
buyMoreLlamas();
}

捕获异常时,可以定义多个异常类型的捕获处理,抛出的异常匹配到一个异常类型后,就不继续往下匹配了。如果你没有指定捕获的异常类型,将匹配任意类型。

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 exception类型 或者catch(e),再或者两个都有的异常捕获写法。on可以区分异常类型,catch可以获取异常对象。

其中,catch可以获取两个对象,第一个是异常对象,第二个是错误堆栈。

try {
// ···
} on Exception catch (e) {
print('Exception details:\n $e');
} catch (e, s) {
print('Exception details:\n $e');
print('Stack trace:\n $s');
}

如果catch后,需要将异常抛出到外层,可以用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();
} try {
breedMoreLlamas();
} catch (e) {
print('Error: $e'); // Handle the exception first.
} finally {
cleanLlamaStalls(); // Then clean up.
}

第七篇翻译 Classes 类 Dart的核心部分