VS Code中Dart自定义异常处理报错:errorMessage方法未定义求解决
解决Dart异常捕获中调用自定义方法的错误
错误原因
Dart中未指定类型的catch块捕获的异常对象默认是Object类型,而Object类没有定义errorMessage方法,因此直接调用会触发类型错误。另外你的DepositException类中errorMessage方法存在无限递归问题(方法内调用自身且无终止条件)。
解决方案
1. 指定捕获的异常类型
使用on 异常类型 catch (e)的语法,明确指定要捕获的异常类型,这样e会被推断为DepositException类型,即可正常调用自定义方法:
void main() { try { depositMoney(-200); } on DepositException catch (e) { print(e.errorMessage()); } } class DepositException implements Exception { // 修正无限递归问题,直接返回错误字符串 String errorMessage() { return "You cannot enter amount less than 0! "; } } void depositMoney(int amount) { if (amount < 0) { throw DepositException(); // Dart 2.12+ 可省略new关键字 } }
2. 在catch块中显式类型转换
如果需要捕获多种异常,可在catch块中将e强制转换为DepositException类型(需确保异常确实是该类型,或添加类型判断避免报错):
void main() { try { depositMoney(-200); } catch (e) { if (e is DepositException) { print(e.errorMessage()); } else { // 处理其他类型异常 print(e.toString()); } } } // 其余代码同方案1
额外优化:使用getter替代方法
自定义异常通常用getter属性来返回错误信息,更符合Dart的编码习惯:
class DepositException implements Exception { String get errorMessage => "You cannot enter amount less than 0! "; } // 调用时直接访问属性 print(e.errorMessage);
内容的提问来源于stack exchange,提问作者Gordon Atsunyo
相关产品推荐
相关产品推荐

