错误处理

Last updated: ... / Reads: 36 Edit

异常

你的 Dart 代码可以抛出和捕获异常。异常是错误 表明发生了意想不到的事情。如果不是异常 捕获时,引发异常的隔离物将被挂起, 通常,隔离物及其程序被终止。

与 Java 相比,Dart 的所有异常都是未经检查的异常。 方法不会声明它们可能会引发哪些异常,而您也不会 需要捕获任何异常。

Dart 提供了 Exception 和 Error 类型,以及许多预定义的子类型。当然,你可以, 定义您自己的例外。但是,Dart 程序可以抛出任何 非 null 对象(而不仅仅是 Exception 和 Error 对象)作为异常。

throw

throw FormatException('Expected at least 1 section');

还可以抛出任意对象:

throw 'Out of llamas!';

生产质量代码通常会引发实现 Error 或 Exception 的类型。

因为抛出异常是一个表达式,所以你可以抛出异常 in => 语句,以及允许表达式的任何其他任何内容:

void distanceTo(Point other) => throw UnimplementedError();

try

捕获或捕获异常会阻止异常 传播(除非重新抛出异常)。 捕获异常使您有机会处理它:

try {
  breedMoreLlamas();
} on OutOfLlamasException {
  buyMoreLlamas();
}

若要处理可能引发多种类型异常的代码,可以 指定多个 catch 子句。与 Thrown 对象的类型处理异常。如果 catch 子句没有 指定一个类型,该子句可以处理任何类型的抛出对象:

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

如前面的代码所示,可以使用其中之一或两者。 在需要指定异常类型时使用。使用场合 异常处理程序需要 Exception 对象。oncatchoncatch

您可以为 指定一个或两个参数。 第一个是抛出的异常, 第二个是堆栈跟踪(StackTrace 对象)。catch()

try {
  // ···
} on Exception catch (e) {
  print('Exception details:\n $e');
} catch (e, s) {
  print('Exception details:\n $e');
  print('Stack trace:\n $s');
}

若要部分处理异常, 同时允许它传播, 使用关键字。rethrow

void misbehave() {
  try {
    dynamic foo = true;
    print(foo++); // Runtime error
  } catch (e) {
    print('misbehave() partially handled ${e.runtimeType}.');
    rethrow; // Allow callers to see the exception.
  }
}

void main() {
  try {
    misbehave();
  } catch (e) {
    print('main() finished handling ${e.runtimeType}.');
  }
}

最后

若要确保某些代码在引发异常时都能运行,请使用 一个子句。如果没有子句与异常匹配,则 异常在子句运行后传播:finallycatchfinally

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

该子句在任何匹配的子句之后运行:finallycatch

try {
  breedMoreLlamas();
} catch (e) {
  print('Error: $e'); // Handle the exception first.
} finally {
  cleanLlamaStalls(); // Then clean up.
}

要了解更多信息,请查看核心库异常文档。

断言

在开发过程中,使用断言 语句— —到 如果布尔条件为 false,则中断正常执行。assert(, );

// Make sure the variable has a non-null value.
assert(text != null);

// Make sure the value is less than 100.
assert(number < 100);

// Make sure this is an https URL.
assert(urlString.startsWith('https'));

要将消息附加到断言, 添加一个字符串作为第二个参数(可选使用尾随逗号):assert

assert(urlString.startsWith('https'),
    'URL ($urlString) should start with "https".');

的第一个参数可以是任何表达式 解析为布尔值。如果表达式的值 为 true,则断言成功并执行 继续。如果为 false,则断言将失败,并引发异常 (AssertionError) 。assert

断言究竟何时起作用? 这取决于您使用的工具和框架:

  • Flutter 在调试模式下启用断言。
  • 默认情况下,仅开发工具(如 webdev serve)通常启用断言。
  • 一些工具,比如 dart run 和 dart compile js 支持通过命令行标志进行断言: .--enable-asserts

在生产代码中,断言将被忽略,并且 不计算要的参数。assert


Comments

Make a comment