Dart —— 异常 throw ,try , catch ,finally ,on Exception , rethrow

释放双眼,带上耳机,听听看~!

Dart汇总请点击这里

异常

Dart 代码可以抛出和捕获异常。 异常表示一些未知的错误情况。 如果异常没有被捕获, 则异常会抛出, 导致抛出异常的代码终止执行。

和 Java 有所不同, Dart 中的所有异常是非检查异常。 方法不会声明它们抛出的异常, 也不要求捕获任何异常。

Dart 提供了 Exception 和 Error 类型, 以及一些子类型。 当然也可以定义自己的异常类型。 但是,此外 Dart 程序可以抛出任何非 null 对象, 不仅限 Exception 和 Error 对象。

throw

下面是关于抛出或者 引发 异常的示例:


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

也可以抛出任意的对象:


1
2
3
1throw 'Out of llamas!';
2
3

提示: 高质量的生产环境代码通常会实现 Error 或 Exception 类型的异常抛出。

因为抛出异常是一个表达式, 所以可以在 => 语句中使用,也可以在其他使用表达式的地方抛出异常:


1
2
3
1void distanceTo(Point other) => throw UnimplementedError();
2
3

catch

捕获异常可以避免异常继续传递(除非重新抛出( rethrow )异常)。 可以通过捕获异常的机会来处理该异常:


1
2
3
4
5
6
7
1try {
2  breedMoreLlamas();
3} on OutOfLlamasException {
4  buyMoreLlamas();
5}
6
7

通过指定多个 catch 语句,可以处理可能抛出多种类型异常的代码。 与抛出异常类型匹配的第一个 catch 语句处理异常。 如果 catch 语句未指定类型, 则该语句可以处理任何类型的抛出对象:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1try {
2  breedMoreLlamas();
3} on OutOfLlamasException {
4  // 一个特殊的异常
5  buyMoreLlamas();
6} on Exception catch (e) {
7  // 其他任何异常
8  print('Unknown exception: $e');
9} catch (e) {
10  // 没有指定的类型,处理所有异常
11  print('Something really unknown: $e');
12}
13
14

如上述代码所示,捕获语句中可以同时使用 on和 catch ,也可以单独分开使用。 使用on 来指定异常类型, 使用 catch 来 捕获异常对象。

catch()函数可以指定1到2个参数, 第一个参数为抛出的异常对象, 第二个为堆栈信息 ( 一个 StackTrace 对象 )。


1
2
3
4
5
6
7
8
9
10
1try {
2  // ···
3} on Exception catch (e) {
4  print('Exception details:\n $e');
5} catch (e, s) {
6  print('Exception details:\n $e');
7  print('Stack trace:\n $s');
8}
9
10

如果仅需要部分处理异常, 那么可以使用关键字 rethrow 将异常重新抛出。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1void misbehave() {
2  try {
3    dynamic foo = true;
4    print(foo++); // Runtime error
5  } catch (e) {
6    print('misbehave() partially handled ${e.runtimeType}.');
7    rethrow; // Allow callers to see the exception.
8  }
9}
10
11void main() {
12  try {
13    misbehave();
14  } catch (e) {
15    print('main() finished handling ${e.runtimeType}.');
16  }
17}
18
19

finally

不管是否抛出异常, finally 中的代码都会被执行。 如果 catch 没有匹配到异常, 异常会在 finally 执行完成后,再次被抛出:


1
2
3
4
5
6
7
8
1try {
2  breedMoreLlamas();
3} finally {
4  // Always clean up, even if an exception is thrown.
5  cleanLlamaStalls();
6}
7
8

任何匹配的 catch 执行完成后,再执行 finally :


1
2
3
4
5
6
7
8
9
1try {
2  breedMoreLlamas();
3} catch (e) {
4  print('Error: $e'); // Handle the exception first.
5} finally {
6  cleanLlamaStalls(); // Then clean up.
7}
8
9

更多详情,请参考 Exceptions 章节。

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++ explicit关键字

2022-1-11 12:36:11

安全经验

spring-oauth-server 0.5 发布,OAuth2 与 Spring Security 安全应用整合

2016-6-2 11:12:22

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索