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

Dart Try-Catch

A try-catch statement is a pair of blocks that handles an error in a planned way. An on clause in front of a catch block names one type to catch.

Catching one named type

The on clause names the type Exception. The catch block prints e, and the output shows the word Exception with its message.

void main() {
  try {
    throw Exception('Empty name');
  } on Exception catch (e) {
    print(e);
  }
}

A plain catch for any kind

int.parse gets text that is not a number and throws. The plain catch has no type name and still catches the throw.

void main() {
  try {
    var number = int.parse('abc');
    print(number);
  } catch (e) {
    print('That text is not a number');
  }
}

The specific clause runs first

The throw is an Exception, so the on Exception block matches first. The plain catch below it does not run.

void main() {
  try {
    throw Exception('Full');
  } on Exception catch (e) {
    print('Caught as Exception');
  } catch (e) {
    print('Caught another kind');
  }
}

finally on the success path

Nothing throws in the try block, so the catch block stays unused. The finally block still runs after the try block.

void main() {
  try {
    print('Work done');
  } catch (e) {
    print('Work failed');
  } finally {
    print('Finally runs');
  }
}

Example

void main() {
  try {
    var code = int.parse('xy');
    print(code);
  } on Exception catch (e) {
    print('Caught as Exception');
  } catch (e) {
    print('Caught another kind');
  } finally {
    print('Cleanup done');
  }
  print('Program continues');
}

Key points

  • try: the block that holds the code to watch.
  • catch (e): a block that runs after any throw in its try block.
  • on Exception catch (e): a catch block that runs only for the type Exception.
  • In on Exception catch (e), the name e holds the caught exception.
  • Printing an Exception value shows its message after the word Exception.
  • Use finally for a block that runs after the try block in every case.

In this example, int.parse gets the text xy. That text is not a number, so parse throws a FormatException. FormatException is a kind of Exception, so the on Exception block runs and prints Caught as Exception. The finally block prints Cleanup done. The last line prints Program continues.

Note

Catch blocks run from top to bottom, so a specific on clause goes before a plain catch.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

Which block runs after a try block in both success and failure?