๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Dart Catching in Depth

One try block can carry several on clauses and a two-value catch. Each clause handles the kind of problem it names.

Most specific clause first

The FormatException clause stands before the plain catch. Each failed try lands in the clause that matches it.

void main() {
  try {
    int.parse('abc');
  } on FormatException {
    print('That text is not a number');
  } catch (e) {
    print('Something else went wrong');
  }
  try {
    throw 'plain problem';
  } on FormatException {
    print('That text is not a number');
  } catch (e) {
    print('Caught a plain value: $e');
  }
}

The two-value catch

The catch binds both the error and a stack trace. This program prints the error and a fixed line about the trace.

void main() {
  try {
    throw 'bad input';
  } catch (e, s) {
    print('Error was: $e');
    print('A stack trace was captured');
  }
}

Finally without a catch

The inner try has finally but no catch. The finally line prints, then the error reaches the outer catch.

void main() {
  try {
    try {
      throw 'door locked';
    } finally {
      print('cleanup ran');
    }
  } catch (e) {
    print('outer caught: $e');
  }
}

The combined on and catch form

The clause names the type and binds the value in one line. The print shows the type name of the caught error.

void main() {
  try {
    int.parse('12x');
  } on FormatException catch (e) {
    print(e.runtimeType);
  }
}

Example

void checkAge(String text) {
  try {
    var age = int.parse(text);
    print('Age is $age');
  } on FormatException catch (e) {
    print('Not a whole number');
  } finally {
    print('check finished');
  }
}

void main() {
  checkAge('21');
  checkAge('two');
}

Key points

  • on clauses run in order, so the most specific type goes first.
  • A later plain catch handles anything the on clauses missed.
  • catch (e, s) receives the error and a stack trace together.
  • A try with finally and no catch still runs the finally block before the error travels on.
  • The combined form on X catch (e) names the type and binds the value in one line.

In this example, the first call parses the text and prints the age. The second call fails to parse, so the on clause prints its line. The finally block prints after both calls.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

In catch (e, s), what is s?