Dart从2.10升级到2.13后自定义Exception类代码运行报错如何解决
问题原因
- Dart 2.12版本正式引入空安全特性的同时,收紧了全局类型校验规则:catch块默认捕获的对象类型为
Object(Dart中允许抛出任意类型的对象,不局限于Exception子类),编译器会直接校验Object类是否存在调用的方法,老版本宽松的类型校验不会拦截这类写法,所以升级后报错。
可选用的解决方案
方案1(最推荐):捕获时指定异常类型
直接限定catch块只捕获AmtException类型的异常,编译器就能识别到errMsg方法:
class AmtException implements Exception { String errMsg() => 'Amount should be greater than zero'; } void withdraw_amt(int amt) { if (amt <= 0) { throw AmtException(); } } void main() { try { withdraw_amt(-1); } on AmtException catch (e) { print(e.errMsg()); } finally { print('Ending requested operation.....'); } }
方案2:类型判断后调用
如果需要捕获所有类型的异常,可以先判断类型再调用对应方法,避免类型错误:
try { withdraw_amt(-1); } catch (e) { if (e is AmtException) { print(e.errMsg()); } else { // 处理其他类型的异常 print(e); } } finally { print('Ending requested operation.....'); }
方案3(不推荐):强制类型转换
如果你能确定抛出的异常一定是AmtException类型,可以用as强制转换,但是如果实际抛出其他类型对象会触发运行时错误:
try { withdraw_amt(-1); } catch (e) { print((e as AmtException).errMsg()); } finally { print('Ending requested operation.....'); }
内容的提问来源于stack exchange,提问作者Kisah Tegar Putra Abdi
相关产品推荐
相关产品推荐

