在Dart中扩展Exception类 [英] Extending the Exception class in Dart

查看:150
本文介绍了在Dart中扩展Exception类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试扩展Exception类并且无法弄清楚原因时,我总是收到错误消息。
这是我的自定义异常的代码:

I keep getting an error when I try to extend the Exception class and can't figure out why. Here is the code for my custom exception:

class MyException extends Exception {
  String msg;
  MyException(this.msg);
  String toString() => 'FooException: $msg';
}

该错误在构造函数周围解决。它抱怨说生成的构​​造函数'Exception([dynamic message])-> Exception'可能是工厂发现的。我该如何解决?

The error resolves around the constructor. It complains that "The generative constructor 'Exception([dynamic message]) -> Exception' expected, but factory found". How do I fix this?

推荐答案

您几乎完全正确。您需要实现异常,而不是扩展它。这应该起作用:

You have it almost right. You need to implement Exception rather than extend it. This should work:

class MyException implements Exception {
  final String msg;
  const MyException(this.msg);
  String toString() => 'FooException: $msg';
}

您不必制作 msg final或构造函数 const ,但可以。这是Exception类的实现示例(来自dart:core库):

You don't have to make msg final or the constructor const, but you can. Here is an example of an implementation of the Exception class (from the dart:core library):

class FormatException implements Exception {
  /**
   * A message describing the format error.
   */
  final String message;

  /**
   * Creates a new FormatException with an optional error [message].
   */
  const FormatException([this.message = ""]);

  String toString() => "FormatException: $message";
}

这篇关于在Dart中扩展Exception类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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