likes
comments
collection
share

Dart 知识点 - 异常处理

作者站长头像
站长
· 阅读数 6

推荐使用线上编辑器 dartpad.cn 进行学习,测试~

Dart 将异常封装到一个类中,出现错误时就会抛出异常消息。

使用 throw 抛出异常

使用 throw 抛出异常,但是不推荐使用。还不如一个 print 来得实在。

void main() {
//   errorHere(); // Uncaught Error: First error
  errorThere(); // Uncaught Error: Exception: Second error
}

void errorHere() {
  throw('First error');
}

void errorThere() => throw Exception('Second error');

捕获异常

当发生时候,我们捕获到错误,然后将错误另行处理。错误的捕获是一个自下而上的操作,如果所有的方法都处理不了错误,则程序终止。

try-catch 语句

其语法格式如下:

try {
  // 相关逻辑代码
} catch(error, stackTrace) {
  // 处理错误
}
  • error 是异常对象
  • stackTraceStackTrace 对象,异常的堆栈信息

比如:

void main() {
  try{
    throw('This is a Demo.');
  } catch(error, stackTrack) {
    // 输出异常信息
    print('error: ${error.toString()}'); // error: This is a Demo.
    // 输出堆栈信息
    print('stackTrack: ${stackTrack.toString()}');
//     stackTrack: This is a Demo.
//     at Object.wrapException (<anonymous>:335:17)
//     at main (<anonymous>:2545:17)
//     at <anonymous>:3107:7
//     at <anonymous>:3090:7
//     at dartProgram (<anonymous>:3101:5)
//     at <anonymous>:3109:3
//     at replaceJavaScript (https://dartpad.cn/scripts/frame.js:19:19)
//     at messageHandler (https://dartpad.cn/scripts/frame.js:80:13)
  }
}

try-on-catch 语句

try 代码块中有很多语都发生了错误,发生错误的种类又不同,我们可以通过 on 来实现。

try {
  // 逻辑代码
} on ExceptionType catch(error) {
  // 处理代码块
} on ExceptionType catch(error) {
  // 处理代码块
} catch(error, stackTrace) {
  // 处理代码块
}
  • ExceptionType 表示错误类型。

Dart 支持的内置错误有:

错误描述
DefferedLoadException延迟的库无法加载
FormatException转换失败
IntegerDivisionByZeroException当数字除以零时抛出错误
IOException输入输出错误
IsolateSpawnException无法创建隔离抛出错误
Timeout异步超时抛出错误

finally 语句

无论是否有异常,都会执行 finally 内部的语句。

try {
  // 逻辑代码
} catch(error, stackTrace) {
  // 错误处理
} finally {
  // 里面的代码块,无论正确还是错误都会处理
}

finally 这个很容易理解,只需要记住上面的语法,使用就行了。

自定义异常

上面👆我们已经介绍了 Dart 的内置异常,但是远远不够使用。那么,我们能够自定义自己的异常?

是的,我们可以按照实际情况自定义异常,Dart 中的每个异常都是内置类 Exception 的子类型。我们可以这样定义:

void main() {
  try {
    throw new MyException('This is a Demo.');
  } catch(error) {
    print(error.toString()); // This is a Demo.
  }
  
  try {
    throw new MyException('');
  } catch(error) {
    print(error.toString()); // My Exception.
  }
}

// 自定义异常类
class MyException implements Exception {
  // 异常信息
  String msg = '';
  
  MyException(this.msg);
  
  // 重写 toString 方法
  @override
  String toString() {
    if(this.msg.isEmpty) {
      return 'My Exception.';
    } else {
      return this.msg;
    }
  }
}

往期精彩推荐

如果读者觉得文章还可以,不防一键三连:关注➕点赞➕收藏