Dart中表示异常的类有两个,分别是Exception和Error。
Exception是由VM或者dart code中抛出的。
Exception主要用来表示用户程序编写过程中产生的异常,是可以定位到的可以解决的异常。通常来说Exception中包含了足够的信息来方便用户来定位异常点。
所以Exception通常是需要被catch的。但是和java不同的是,dart中所有的异常都是unchecked 异常,也就是说dart中的异常并不强制要求被捕获,是否捕获异常是由程序员自行决定的。
dart中也有很多Exception的子类,比如FormatException来表示各种不同的异常情形。
dart中的Error表示的是一个严重的错误,Error是应该在程序编写过程中需要避免的。
**dart中的Error并不需要被捕获,**因为发生了Error就表示程序出现了非常严重的错误,已经无法运行下去了。
在dart中,不仅仅可以throw Exception或者Error,任何一个Object都可以throw出去
void testException(int age) {
if (age < 0) {
throw new FormatException("数字格式错误!"); //打印输出结果:FormatException: 数字格式错误!
//throw "数字格式错误!"//打印输出结果: 数字格式错误!
}
}
//因为抛出异常是一个表达式,所以可以在 => 语句中使用,也可以在其他使用表达式的地方抛出异常
void testException1(int age)=> age < 0? throw new FormatException("数字格式错误!"):age;
void main(){
try {
testException1(-2);
} catch (e) {
print(e);
}
}
**try块包裹可能出现异常的代码。需要指定异常类型时使用on块。**catch块捕获异常对象,进而进行处理。
void getException1() {
try {
4 ~/ 0;
} on IntegerDivisionByZeroException catch (e) {
//on…catch块,只捕获紧跟on后面的异常对象!
//捕获指定异常
print("caught it:" + e.toString());
}
}
对于可以抛出多种异常类型的代码,也可以指定多个on/catch 语句,
on块和catch块是相互包含的,即try块可以与on块和catch块相关联。
每个语句分别对应一个异常类型,如果 catch 语句没有指定异常类型则表示可以捕获任意异常类型
void getException2() {
try {
4 ~/ 0;
} on IntegerDivisionByZeroException catch (e) {
// 捕获特定的异常
print("捕获特定的异常:" + e.toString());
} on Exception catch (e) {
// 捕获其他的Exception
print('其他的异常: $e');
} catch (e) {
// 处理剩下的异常
print('剩下的异常: $e');
} finally {
//和JAVA一样,dart中也有Finally,用来进行最终的处理。Finally会在所有的catch语句执行完毕之后执行:
print("一定会走的finally");
}
}
main(){
try {
getException2();
} catch (e) {
print(e.toString()); //打印输出结果:捕获特定的异常:IntegerDivisionByZeroException
}
}
可以为 catch 方法指定两个参数,第一个参数为抛出的异常对象,第二个参数为栈信息 StackTrace 对象
void getException() {
try {
4 ~/ 0;
} on IntegerDivisionByZeroException catch (e, s) {
// 捕获特定的异常
print("捕获特定的异常:" + e.toString() + " 栈信息:${s.toString()}");
}
}
打印输出结果:
捕获特定的异常:IntegerDivisionByZeroException 栈信息:#0 int.~/ (dart:core-patch/integers.dart:30:7)
#1 getException
bin\Exception_demo.dart:90
#2 main
bin\Exception_demo.dart:34
#3 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:281:32)
#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
所以dart推荐抛出自定义异常,也就是说根据业务需要去创建Exception对应的类,然后根据业务需要进行抛出。
class MyExp implements Exception {
String errMsg() => '这是一个自定义异常';
}
void getException3(int num) {
if (num < 60) {
throw MyExp();
}
}
main(){
try {
getException3(59);
} on MyExp catch (e) {
print(e.errMsg());
}
//输出结果:这是一个自定义异常
}
关键字 rethrow 可以将捕获的异常再次抛出: 调用的地方需要try catch
void getException() {
try {
4 ~/ 0;
} on IntegerDivisionByZeroException catch (e) {
// 捕获特定的异常
print("捕获特定的异常:" + e.toString());
rethrow;/再次抛出异常,上层处理
}
}
void main(){
try {
getException();
} catch (e) {
print("再次捕获的异常:${e.toString()}");
}
}
//输出打印:
捕获特定的异常:IntegerDivisionByZeroException
再次捕获的异常:IntegerDivisionByZeroException