• Exception
  • Error
  • 还有些子类

  • dart 可以抛出任意非 null 对象

Throw

  1. throw FormatException('Expected at least 1 section');
  • 抛出任意对象
  1. throw 'Out of llamas!';
  • =>
  1. void distanceTo(Point other) => throw UnimplementedError();

Catch

  1. try {
  2. breedMoreLlamas();
  3. } on OutOfLlamasException {
  4. buyMoreLlamas();
  5. }
  • 处理异常
  1. try {
  2. breedMoreLlamas();
  3. } on OutOfLlamasException {
  4. // A specific exception
  5. buyMoreLlamas();
  6. } on Exception catch (e) {
  7. // Anything else that is an exception
  8. print('Unknown exception: $e');
  9. } catch (e) {
  10. // No specified type, handles all
  11. print('Something really unknown: $e');
  12. }
  • catch 可以接受两个对象
    • 异常对象
    • stack trace
  1. try {
  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. }
  • 处理异常后还可抛出
  1. void 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. void main() {
  11. try {
  12. misbehave();
  13. } catch (e) {
  14. print('main() finished handling ${e.runtimeType}.');
  15. }
  16. }

Finally

  • 异常没有被捕捉, 那么异常在 finally 之后再传播
  1. try {
  2. breedMoreLlamas();
  3. } finally {
  4. // Always clean up, even if an exception is thrown.
  5. cleanLlamaStalls();
  6. }
  • finally 在异常被捕获后运行
  1. try {
  2. breedMoreLlamas();
  3. } catch (e) {
  4. print('Error: $e'); // Handle the exception first.
  5. } finally {
  6. cleanLlamaStalls(); // Then clean up.
  7. }