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

Dart Exceptions

An exception is an error signal that a program can throw and catch. A throw stops the normal flow at that point and hands control to a catch block.

Throwing and catching in one place

The throw line creates an Exception with the message Bad value. The catch block runs and prints one plain line.

void main() {
  try {
    throw Exception('Bad value');
  } catch (e) {
    print('Caught an error');
  }
}

A function that throws

checkAge throws when the age is below zero. main catches that exception and prints Invalid age.

void checkAge(int age) {
  if (age < 0) {
    throw Exception('Age cannot be negative');
  }
  print('Age accepted');
}

void main() {
  try {
    checkAge(-3);
  } catch (e) {
    print('Invalid age');
  }
}

The program continues after a catch

The catch block prints its line first. The print after the blocks then runs as normal.

void main() {
  try {
    throw Exception('Missing name');
  } catch (e) {
    print('Name is missing');
  }
  print('Program continues');
}

Example

void checkScore(int score) {
  if (score > 100) {
    throw Exception('Score is too high');
  }
  print('Score accepted');
}

void main() {
  try {
    checkScore(120);
  } catch (e) {
    print('Score rejected');
  }
  print('Checking done');
}

Key points

  • Exception: a type that carries an error message as text.
  • Use throw to send an exception out of the code that found the problem.
  • Use throw Exception with a message to create and throw an exception in one line.
  • try: a block that holds code that may throw.
  • catch: a block that runs when its try block throws.
  • Code after a catch block runs as normal once the catch block ends.

In this example, main calls checkScore with the value 120. The score is above 100, so checkScore throws an Exception. The catch block prints Score rejected. The last print then shows Checking done.

Note

Every throw in this lesson sits inside a try block, so a catch block always handles it.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

Which keyword throws an exception?