飞镖中的自定义异常

时间:2012-11-27 08:21:36

标签: exception-handling dart

我已编写此代码来测试自定义异常如何在dart中运行。

我没有得到所需的输出,有人可以解释我如何处理它?<​​/ p>

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

}

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

3 个答案:

答案 0 :(得分:27)

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

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

答案 1 :(得分:22)

您可以查看Exception part of A Tour of the Dart Language

以下代码按预期工作(控制台中显示custom exception is been obtained):

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

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

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

答案 2 :(得分:3)

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();
相关问题