- Exception
- Error
还有些子类
dart 可以抛出任意非 null 对象
Throw
throw FormatException('Expected at least 1 section');
- 抛出任意对象
throw 'Out of llamas!';
- =>
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');
}
- catch 可以接受两个对象
- 异常对象
- stack trace
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.
}
}
void main() {
try {
misbehave();
} catch (e) {
print('main() finished handling ${e.runtimeType}.');
}
}
Finally
- 异常没有被捕捉, 那么异常在 finally 之后再传播
try {
breedMoreLlamas();
} finally {
// Always clean up, even if an exception is thrown.
cleanLlamaStalls();
}
- finally 在异常被捕获后运行
try {
breedMoreLlamas();
} catch (e) {
print('Error: $e'); // Handle the exception first.
} finally {
cleanLlamaStalls(); // Then clean up.
}