【问题标题】:Dart The function 'errorMessage' isn't definedDart 函数 'errorMessage' 未定义
【发布时间】:2021-05-12 16:06:14
【问题描述】:

我是飞镖新手,我正在 youtube 上学习飞镖。我关注的课程是 2018 年的。他们在视频中创建的程序不起作用。我在所有程序中都面临以下问题。任何人,请指导我为什么程序在其视频中正常运行时显示错误。这是由于飞镖的更新而发生的吗?或任何其他原因?请帮助解决此问题。谢谢! 未定义函数“errorMessage”。 尝试导入定义“errorMessage”的库,将名称更正为现有函数的名称,或者定义一个名为“errorMessage”的函数。

class CustomException implements Exception {
  String errorMessage() {
    return ("Invalid Amount");
  }
}

void AmountException(int amount) {
  if (amount <= 0) {
    throw new CustomException();
  }
}

void main() {
  try {
    AmountException(0);
  } catch (e) {
    print(errorMessage());
  }
}

【问题讨论】:

  • 您没有在异常 (e) 上调用 errorMessage()
  • 那该怎么做。你能解释一下吗?
  • 添加了答案。 :)
  • 感谢兄弟,它的工作
  • 太棒了。如果它有效并且您没有其他问题,请接受我的回答。 :)

标签: dart


【解决方案1】:

您没有在异常上调用errorMessage() 消息。另一个问题是您的catch 设置为处理所有类型的异常。由于Exception 没有errorMessage() 方法,所以不能调用它。

因此,您应该指定要捕获的异常类型,这将允许您对捕获的异常调用 errorMessage() 方法:

class CustomException implements Exception {
  String errorMessage() {
    return ("Invalid Amount");
  }
}

void AmountException(int amount) {
  if (amount <= 0) {
    throw new CustomException();
  }
}

void main() {
  try {
    AmountException(0);
  } on CustomException catch (e) {
    print(e.errorMessage());
  }
}

【讨论】:

    猜你喜欢
    • 2020-09-05
    • 2017-08-19
    • 2021-03-03
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 2019-03-24
    • 2013-06-17
    • 1970-01-01
    相关资源
    最近更新 更多