Dart 代码可以抛出和捕获异常。与 Java 相比,Dart 的所有异常都是未经检查的异常。方法不会声明它们可能会抛出哪些异常,并且您不需要捕获任何异常。
Dart 提供 Exception 和 Error 类型,但你可以抛出任何非空对象:
throw Exception('Something bad happened.');
throw 'Waaaaaaah!';
在处理异常时使用try、on和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');
}
try 关键字的工作方式与大多数其他语言一样。使用 on 关键字按类型过滤特定异常,使用 catch 关键字获取对异常对象的引用。
如果不能完全处理异常,使用rethrow关键字传播异常:
try {
breedMoreLlamas();
} catch (e) {
print('I was just trying to breed llamas!.');
rethrow;
}
无论是否抛出异常都执行代码,请使用finally:
try {
breedMoreLlamas();
} catch (e) {
// ... handle exception ...
} finally {
// Always clean up, even if an exception is thrown.
cleanLlamaStalls();
}
代码示例
在下面实现tryFunction()。它应该执行一个不可信的方法,然后执行以下操作:
- 如果
untrustworthy() 抛出ExceptionWithMessage,请使用异常类型和消息调用logger.logException(尝试使用on 和catch)。
- 如果
untrustworthy() 抛出异常,请使用异常类型调用logger.logException(尝试使用on 处理此异常)。
- 如果
untrustworthy() 抛出任何其他对象,请不要捕获异常。
- 一切都抓到并处理完毕后,致电
logger.doneLogging(尝试使用finally)。
.
typedef VoidFunction = void Function();
class ExceptionWithMessage {
final String message;
const ExceptionWithMessage(this.message);
}
abstract class Logger {
void logException(Type t, [String msg]);
void doneLogging();
}
void tryFunction(VoidFunction untrustworthy, Logger logger) {
try {
untrustworthy();
} on ExceptionWithMessage catch (e) {
logger.logException(e.runtimeType, e.message);
} on Exception {
logger.logException(Exception);
} finally {
logger.doneLogging();