05.Dart - 异常Exception Error

个人学习用
不严谨
学习的话请看别的博客

异常种类

void main(){
  /**
   * Exception 和 Error 两种异常以及他们的一些子类
   *
   */


}

抛出异常

void main() {
  /**
   * 抛出异常
   *
   */

  //throw FormatException("我是FormatException异常");
  //throw "我是文字异常";

  //因为异常是一个表达式,所以可以在其他使用表达式的地方抛出异常
  void printException() => throw "我是异常";

  printException();

}

捕获异常

void main() {
  /**
   *
   */

  try {
    print("1");
  } on Exception catch (e) {
    print(e);
  } on int catch (e) {
    print(e);
  } on String catch (e) {
    print(e);
  } catch (e) {
    print(e);
  }
}

Finally

void main() {
  /**
   * Finaly
   * 可以使用finally语句来包裹确保不管有没有异常都执行的代码
   */

  try {
    breedMoreLlamas();
  } catch (e) {
    print('Error: $e'); // 先处理异常。
  } finally {
    //无论有没有异常,都会执行
    cleanLlamaStalls(); // 然后清理。
  }
}

void breedMoreLlamas() {
  print("1111");
}

void cleanLlamaStalls() {
  print("清理");
}
发布了33 篇原创文章 · 获赞 6 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/zlhyy666666/article/details/104581150