Menu
CoddyTech

异常与恢复

Coddy 面向 C 开发者的 Dart 课程的第 25 课,共 48 课。

C 没有异常:函数通过返回值或 errno 报告失败,每个调用者都会检查它,而清理操作通常通过 goto 跳转到一个共享标签(setjmp 和 longjmp 会跳过该清理操作,因此通常不适合用来处理这种情况)。Dart 会抛出对象,使调用栈展开,直到遇到匹配的处理程序,而且不需要声明已检查异常。类型化处理程序和 finally 支持显式恢复和清理。

使用 on 选择异常类型,并使用 catch 绑定抛出的对象,还可以选择绑定堆栈跟踪。正常完成和常规栈展开时,finally 都会执行清理。处理预期会发生的失败,但不要掩盖编程错误。

完整的 C 程序:

#include <stdio.h>

static int parse_digit(char c, int *out) {
    if (c < '0' || c > '9') return -1;
    *out = c - '0';
    return 0;
}

int main(void) {
    int digit;
    if (parse_digit('x', &digit) != 0) {
        printf("format\n");
        goto cleanup;
    }
    printf("%d\n", digit);
cleanup:
    printf("cleanup\n");
    return 0;
}

完整的 Dart 程序:

void main(){try{throw FormatException('bad');}on FormatException{print('format');}finally{print('cleanup');}}
challenge icon

挑战

简单

实现 divide(int a,int b):除数为零时抛出 ArgumentError,除法有非零余数时抛出 StateError,否则返回整数商。输入包含两个介于 -100 到 100 之间的整数。包装代码会报告 zero、fraction 或商。

不要在可编辑文件中打印内容。提供的 exercise.dart 会解析输入并返回输出;锁定的驱动程序会独立测试公共 API,并在结果后输出一个换行符。

你的代码写在 functions.dart、exercise.dart 中。main.dart 包含提供的输入输出代码,不能编辑。

亲手试试

import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'functions.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
check(divide(15,3)==5);var caught=false;try{divide(1,0);}on ArgumentError{caught=true;}check(caught);
stdout.writeln(solve(input));
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C 开发者的 Dart中的所有课

自己练习: Dart 在线编译器