On this page12 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. What Is an Exception?
  4. 2. try / catch
  5. 3. on: Catch a Specific Type
  6. 4. Several Handlers, and finally
  7. 5. throw: Raise Your Own Error
  8. Code Examples
  9. Common Beginner Mistakes
  10. Practice Questions
  11. Practice Answers
  12. Key Takeaways

Lecture 037: Exception Handling

Day13: Exception Handling
Lecture037 of 057
Estimated video length14 min
TargetDart 3.12
LevelBeginner

A user types "abc" where a number belongs. A file is missing. The internet drops. Things go wrong while a program runs, and without a plan, the program crashes. Exception handling catches the problem, deals with it, and lets the program carry on.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 009 (int.parse), 011 (lists), 020 (loops) and 025 (functions).


Learning Objectives

  • Explain what an exception is
  • Catch exceptions with try / catch
  • Catch specific types with on
  • Run clean-up code with finally
  • Raise your own errors with throw

1. What Is an Exception?

An exception is an error that happens while the program is running. If nothing handles it, the program stops:

dart
void main() {
  print('Start');
  var n = int.parse('12a');
  print('End $n');
}
code
Start
Unhandled exception:
FormatException: Invalid radix-10 number (at character 1)
12a
^

End never prints.

2. try / catch

Put risky code in try. If it throws, Dart jumps straight to catch, and the program continues afterwards:

dart
try {
  var n = int.parse('12a');
  print('Parsed $n');          // skipped, because the line above threw
} catch (e) {
  print('Could not read the number: $e');
}
print('Program keeps going');

Output

code
Could not read the number: FormatException: Invalid radix-10 number (at character 1)
12a
^

Program keeps going

e holds the exception object, so you can print it or inspect it.

3. on: Catch a Specific Type

Different problems throw different types. on Type catches only that type:

dart
try {
  var list = [1, 2, 3];
  print(list[5]);
} on RangeError {
  print('That position does not exist');
}

Combine on and catch to get the object too:

dart
try {
  print(10 ~/ 0);
} on UnsupportedError catch (e) {
  print('Maths problem: $e');   // Maths problem: IntegerDivisionByZeroException
}
Common typeThrown when…
FormatExceptiontext can't be parsed (int.parse('abc'))
RangeErroran index is out of range (list[10])
UnsupportedErroran operation isn't allowed (5 ~/ 0, adding to a const list)
StateErrorsomething is in the wrong state (firstWhere with no match)
ArgumentErrora function got a bad argument

4. Several Handlers, and finally

List specific on clauses first and a general catch last. finally runs every time, whether there was an error or not:

dart
for (var input in ['42', 'abc']) {
  try {
    var value = int.parse(input);
    print('Got $value');
  } on FormatException catch (e) {
    print('Format problem: ${e.message}');
  } catch (e) {
    print('Something else went wrong: $e');
  } finally {
    print('Finished with "$input"');
  }
}

Output

code
Got 42
Finished with "42"
Format problem: Invalid radix-10 number
Finished with "abc"

finally is the place for clean-up that must always happen: closing a file, hiding a loading spinner.

5. throw: Raise Your Own Error

When your function gets something it can't work with, throw an exception:

dart
void checkAge(int age) {
  if (age < 0) {
    throw ArgumentError('Age cannot be negative: $age');
  }
  print('Age ok');
}

try {
  checkAge(-5);
} catch (e) {
  print('Caught: $e');   // Caught: Invalid argument(s): Age cannot be negative: -5
}

throw stops the function at once, like return, but sends an error instead of a value.


Code Examples

Example 1: Safe Withdrawals

dart
double withdraw(double balance, String input) {
  var amount = double.parse(input);
  if (amount <= 0) {
    throw ArgumentError('Amount must be positive');
  }
  if (amount > balance) {
    throw StateError('Insufficient balance');
  }
  return balance - amount;
}

void main() {
  var balance = 5000.0;
  for (var input in ['1500', 'abc', '-20', '9000', '500']) {
    try {
      balance = withdraw(balance, input);
      print('Withdrew $input. Balance: $balance');
    } on FormatException {
      print('"$input" is not a number');
    } on ArgumentError catch (e) {
      print('Rejected $input: ${e.message}');
    } on StateError catch (e) {
      print('Rejected $input: ${e.message}');
    } finally {
      print('--');
    }
  }
}

Output

code
Withdrew 1500. Balance: 3500.0
--
"abc" is not a number
--
Rejected -20: Amount must be positive
--
Rejected 9000: Insufficient balance
--
Withdrew 500. Balance: 3000.0
--

Each bad input is handled differently, balance only changes when the withdrawal succeeds, and the loop never crashes.


Common Beginner Mistakes

1. try with nothing after it

dart
try {
  var n = int.parse('5');
}
code
Error: A try block must be followed by an 'on', 'catch', or 'finally' clause.

2. A general catch before a specific on

dart
try {
  int.parse('x');
} catch (e) {
  print('error');
} on FormatException {
  print('format');
}

It prints error, and the on FormatException clause can never run. dart analyze warns:

code
warning - Dead code: Catch clauses after a 'catch (e)' or an 'on Object catch (e)' are never reached.

Put specific on clauses first, and the general catch last.

3. Catching everything and hiding it: catch (e) {} with an empty body makes bugs invisible. At least print or log the error.

4. Using exceptions for normal checks: if you can check first (int.tryParse, list.isNotEmpty), that's usually simpler than catching.


Practice Questions

  1. What happens to the lines after the failing line inside a try?
  2. What's the difference between catch (e) and on FormatException?
  3. When does a finally block run?
  4. Write code that tries int.parse(text) and prints Not a number if it fails.
  5. Write a function setQuantity(int q) that throws an ArgumentError when q < 1.

Practice Answers

  1. They're skipped. Dart jumps to the matching on / catch.
  2. catch (e) catches anything; on FormatException catches only that type.
  3. Always, whether an exception happened or not.
dart
try {
  print(int.parse(text));
} on FormatException {
  print('Not a number');
}
dart
void setQuantity(int q) {
  if (q < 1) {
    throw ArgumentError('Quantity must be at least 1');
  }
  print('Quantity: $q');
}

Key Takeaways

  • An unhandled exception stops the program.
  • try { risky } catch (e) { handle } catches it and carries on.
  • on Type catches one kind of error; put specific ones first.
  • finally always runs; use it for clean-up.
  • throw raises an error when your code gets something it can't handle.