dart:如何在编译期间捕获TypeError [英] dart: how to catch TypeError during compilation

查看:104
本文介绍了dart:如何在编译期间捕获TypeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码引发运行时错误。

Below code throws a runtime error.

TypeError: FormatException的实例:类型 FormatException不是 CustomException类型的子类型

为什么 Test(e)不会失败,因为e的类型是异常,预期为 CustomException 。如何执行它,使人无法在那里传递 Exception

Why Test(e) does not fail at compilation as type of e is Exception and expected is CustomException. How to enforce it so one cannot pass Exception there.

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 (暂时)具有从父类型到子类型的隐式转换。在您知道自己在做什么的前提下,允许使用表达式,它是所需实际类型的超类型。

Dart has (for now) implicit downcasts from a supertype to a subtype. You are allowed to use an expression which is a super-type of the actual type that is required, under the assumption that you know what you are doing.

在这里,您有一个带有静态值的值键入 Exception (捕获的 e ),然后将其传递给需要 CustomException ,它是 Exception 的子类型。
语言允许这样做,但是会插入运行时向下转换(相当于 e为CustomException )。强制转换失败,因为该值实际上是 FormatException

Here you have a value with static type Exception (the e that was caught), and you pass it to a constructor requiring a CustomException, which is a subtype of Exception. The language allows this, but inserts a run-time downcast (equivalent to e as CustomException). That cast fails because the value is actually a FormatException.

使用即将到来的null安全功能,将删除隐式向下转换,除非从 dynamic (因为 dynamic 始终关闭静态类型检查)。发生这种情况时, Test(e)调用将无效。在此之前,该代码将编译并在运行时失败。

With the up-coming null safety feature, implicit downcasts will be removed except from dynamic (because dynamic turns off static type checks anyway). When that happens, the Test(e) invocation becomes invalid. Until then, this code compilers and fails at run-time.

在此之前,您可以通过在 analysis_options.yaml 文件

Until then, you can get the analyzer to warn you about implicit calls by configuring it in the analysis_options.yaml file

这篇关于dart:如何在编译期间捕获TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆