dart:如何在编译期间捕获TypeError
下面的代码抛出一个运行时错误dart:如何在编译期间捕获TypeError,dart,Dart,下面的代码抛出一个运行时错误 TypeError:FormatException的实例:“FormatException”类型不是“CustomException”类型的子类型。 为什么Test(e)在编译时没有失败,因为e的类型是Exception,而预期的类型是CustomException。如何强制执行它,以便无法在那里传递异常 abstract class CustomException implements Exception { String get code; } class
TypeError:FormatException的实例:“FormatException”类型不是“CustomException”类型的子类型。
为什么Test(e)
在编译时没有失败,因为e的类型是Exception
,而预期的类型是CustomException
。如何强制执行它,以便无法在那里传递异常
abstract class CustomException implements Exception {
String get code;
}
class Test {
final CustomException ex;
Test(this.ex);
}
void main() {
try {
throw new FormatException();
} on Exception catch (e) {
final t = Test(e);
print('message: $t');
}
}
Dart(目前)具有从超类型到子类型的隐式降级。您可以使用一个表达式,该表达式是所需实际类型的超级类型,前提是您知道自己在做什么
这里有一个静态类型为Exception
(捕获的e
)的值,然后将其传递给需要CustomException
的构造函数,该构造函数是Exception
的子类型。
该语言允许这样做,但会插入运行时向下转换(相当于e as CustomException
)。该转换失败,因为该值实际上是FormatException
使用即将推出的空安全功能,除了dynamic
(因为dynamic
无论如何都会关闭静态类型检查)之外,隐式降级将被删除。发生这种情况时,Test(e)
调用将无效。在此之前,此代码将编译并在运行时失败
在此之前,您可以通过在文件Disable implicit casts:@jamesdlin中配置analyzer来警告您有关隐式调用的信息,这很好,而且似乎很有效。得到了很多隐式转换错误,将测试所有重构。请也给我一个答案,这样我就可以接受了。非常感谢。