【问题标题】:How to create a custom exception and handle it in dart如何创建自定义异常并在 dart 中处理它
【发布时间】:2012-11-14 19:45:16
【问题描述】:

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

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

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

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

【问题讨论】:

  • 您是否定义了customException 类?如果是,您能否将其代码添加到您的问题中。
  • 类 customException 实现异常 { String _message = ""; customException([this._message]);字符串 toString() => "LatLngException: message=${_message}"; }我使用@AlexandreArdhuin 定义的这段代码来解决这个问题是正确的

标签: flutter dart exception try-catch


【解决方案1】:

您还可以创建抽象异常。

灵感来自async 包中的TimeoutException(阅读Dart APIDart SDK 上的代码)。

abstract class IMoviesRepoException implements Exception {
  const IMoviesRepoException([this.message]);

  final String? message;

  @override
  String toString() {
    String result = 'IMoviesRepoExceptionl';
    if (message is String) return '$result: $message';
    return result;
  }
}

class TmdbMoviesRepoException extends IMoviesRepoException {
  const TmdbMoviesRepoException([String? message]) : super(message);
}

【讨论】:

    【解决方案2】:

    Dart 代码可以抛出和捕获异常。与 Java 相比,Dart 的所有异常都是未经检查的异常。方法不会声明它们可能会抛出哪些异常,并且您不需要捕获任何异常。

    Dart 提供 ExceptionError 类型,但你可以抛出任何非空对象:

    throw Exception('Something bad happened.');
    throw 'Waaaaaaah!';
    

    在处理异常时使用tryoncatch关键字:

    try {
      breedMoreLlamas();
    } on OutOfLlamasException {
      // A specific exception
      buyMoreLlamas();
    } on Exception catch (e) {
      // Anything else that is an exception
      print('Unknown exception: $e');
    } catch (e) {
      // No specified type, handles all
      print('Something really unknown: $e');
    }
    

    try 关键字的工作方式与大多数其他语言一样。使用 on 关键字按类型过滤特定异常,使用 catch 关键字获取对异常对象的引用。

    如果不能完全处理异常,使用rethrow关键字传播异常:

    try {
      breedMoreLlamas();
    } catch (e) {
      print('I was just trying to breed llamas!.');
      rethrow;
    }
    

    无论是否抛出异常都执行代码,请使用finally

    try {
      breedMoreLlamas();
    } catch (e) {
      // ... handle exception ...
    } finally {
      // Always clean up, even if an exception is thrown.
      cleanLlamaStalls();
    }
    

    代码示例

    在下面实现tryFunction()。它应该执行一个不可信的方法,然后执行以下操作:

    • 如果untrustworthy() 抛出ExceptionWithMessage,请使用异常类型和消息调用logger.logException(尝试使用oncatch)。
    • 如果untrustworthy() 抛出异常,请使用异常类型调用logger.logException(尝试使用on 处理此异常)。
    • 如果untrustworthy() 抛出任何其他对象,请不要捕获异常。
    • 一切都抓到并处理完毕后,致电logger.doneLogging(尝试使用finally)。

    .

    typedef VoidFunction = void Function();
    
    class ExceptionWithMessage {
      final String message;
      const ExceptionWithMessage(this.message);
    }
    
    abstract class Logger {
      void logException(Type t, [String msg]);
      void doneLogging();
    }
    
    void tryFunction(VoidFunction untrustworthy, Logger logger) {
      try {
        untrustworthy();
      } on ExceptionWithMessage catch (e) {
        logger.logException(e.runtimeType, e.message);
      } on Exception {
        logger.logException(Exception);
      } finally {
        logger.doneLogging();
    

    【讨论】:

      【解决方案3】:

      如果您不关心异常的类型,则不需要异常类。只需像这样触发一个异常:

      throw ("This is my first general exception");
      

      【讨论】:

      • reference 表示“Dart 程序可以抛出任何非空对象——不仅仅是 Exception 和 Error 对象——作为异常。” (强调我的),我已经对您的帖子进行了编辑,因为这里抛出的对象的实际类型是 String,您可以通过以下代码 sn-p 验证:void main() { try { throw ("Your description is a String");} catch (e) { print(e.runtimeType); } }跨度>
      【解决方案4】:

      你可以看看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');
      }
      

      【讨论】:

      • 我希望我的异常从 Exception 类继承。
      • 仅供参考:Dart 程序可以抛出任何非空对象——不仅仅是异常和错误对象——作为异常
      • @Vickyonit 不继承 Exception 类,而是实现它。此外,您可能还需要考虑向该类添加代码。
      • 您不想将异常的成员标记为final吗?
      • @OlegSilkin 是的,除非突变是必需的,否则总是让事情成为最终的。异常永远不应该变异。
      猜你喜欢
      • 2017-11-09
      • 2023-03-07
      • 2015-06-24
      • 2019-12-20
      • 2021-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      相关资源
      最近更新 更多