Dart基础(五)-错误和异常

2022-01-07  本文已影响0人  苍眸之宝宝

简介:

您的Dart代码可以抛出和捕获异常。异常是指示发生了意外情况的错误。如果未捕获异常,则引发异常的隔离程序将被挂起,并且通常会终止隔离程序及其程序。

与Java相反,Dart的所有异常都是未检查的异常。方法不声明它们可能抛出的异常,也不需要捕获任何异常。

Dart提供了异常和错误类型,以及许多预定义的子类型。当然,您可以定义自己的异常。然而,Dart程序可以抛出任何非空对象——不仅仅是Exception和Error对象——作为异常。

  总结一下要点:

异常的处理:

  Dart中处理异常的方式:

divide(int a, int b) {
  if (b == 0) {
    throw new IntegerDivisionByZeroException();
  }
  return a / b;
}

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

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

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 Exception catch (e) {
  print('Exception details:\n $e');
} catch (e, s) {  // 异常,异常堆栈
  print('Exception details:\n $e');
  print('Stack trace:\n $s');
}

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

猜你喜欢

热点阅读