如何创建自定义异常并在Dart中处理它 [英] How to create a custom exception and handle it in dart

查看:49
本文介绍了如何创建自定义异常并在Dart中处理它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了这段代码来测试自定义异常在dart中的工作方式.

I have written this code to test how custom exceptions are working in the dart.

我没有得到想要的输出,有人可以向我解释如何处理吗?

I'm not getting the desired output could someone explain to me how to handle it??

void main() 
{   
  try
  {
    throwException();
  }
  on customException
  {
    print("custom exception is been obtained");
  }
  
}

throwException()
{
  throw new customException('This is my first custom exception');
}

推荐答案

您可以查看

You can look at the Exception part of A Tour of the Dart Language.

以下代码按预期工作(在控制台中显示了自定义异常):

The following code works as expected (custom exception has been obtained is displayed in console) :

class CustomException implements Exception {
  String cause;
  CustomException(this.cause);
}

void main() {
  try {
    throwException();
  } on CustomException {
    print("custom exception has been obtained");
  }
}

throwException() {
  throw new CustomException('This is my first custom exception');
}

这篇关于如何创建自定义异常并在Dart中处理它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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