flutter - 如何创建自定义异常并在 dart 中处理它

标签 flutter dart exception try-catch

我编写了这段代码来测试自定义异常在 dart 中的工作方式。
我没有得到所需的输出,有人可以向我解释如何处理吗??

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

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

最佳答案

你可以看看Exception part of A Tour of the Dart Language .
以下代码按预期工作(custom exception has been obtained 显示在控制台中):

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');
}

关于flutter - 如何创建自定义异常并在 dart 中处理它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13579982/

相关文章:

dart - 检查聚合物元素中的对象类型

android - 异步查询处理程序中的异常处理

Java 异常 - TransactionRolledbackLocalException

flutter - Stack 内的 ListView.builder 返回对 null 值使用的 Null 检查错误

flutter - 不并行执行多个异步功能Dart/Flutter

dart - 如何在Dart语言中创建多维LIsts?

java - 如何摆脱仅在 Debug模式下在 Android 应用程序中遇到的 ClassNotFoundException?

flutter - Dart 中 getter 和常规方法的区别

flutter - flutter-web-避免在通过浏览器的地址栏以其他路由启动应用程序启动时启动initialRoute吗?

firebase - 如何保持用户在Flutter中登录?