On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Why Your Own Exception?
  4. 2. Writing One
  5. 3. Throwing and Catching It
  6. Code Examples
  7. Common Beginner Mistakes
  8. Assignment
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 038: Assignment: A Custom Exception Class

Day13: Exception Handling
Lecture038 of 057
Estimated video length12 min
TargetDart 3.12
LevelBeginner

StateError('Insufficient balance') works, but it doesn't say how much was missing, and code can't tell it apart from any other StateError. Your own exception class can carry exactly the details your app needs, and be caught by name. This lecture ends with an assignment.

Contents

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


Prerequisites

Lectures 030–035 (classes, constructors, getters) and 037 (exception handling).


Learning Objectives

  • Create an exception class that implements Exception
  • Give it fields that describe the problem
  • Override toString() so it prints a useful message
  • Throw it, and catch it by name with on

1. Why Your Own Exception?

Built-in errorYour own exception
StateError('Insufficient balance')InsufficientBalanceException(balance, requested)
only a messagereal fields: balance, requested, shortBy
caught as one of many StateErrorscaught exactly: on InsufficientBalanceException

2. Writing One

An exception is an ordinary class that implements Exception (the interface Dart uses for errors that are meant to be caught):

dart
class InsufficientBalanceException implements Exception {
  final double balance;
  final double requested;

  InsufficientBalanceException(this.balance, this.requested);

  double get shortBy => requested - balance;

  @override
  String toString() =>
      'InsufficientBalanceException: requested Rs $requested, balance Rs $balance (short by Rs $shortBy)';
}

class InvalidAmountException implements Exception {
  final String message;
  InvalidAmountException(this.message);

  @override
  String toString() => 'InvalidAmountException: $message';
}
  • Fields carry the details.
  • toString() decides what print(e) shows. Without it, you'd only see Instance of 'InsufficientBalanceException'.

3. Throwing and Catching It

dart
class Account {
  final String owner;
  double balance;
  Account(this.owner, this.balance);

  void withdraw(double amount) {
    if (amount <= 0) {
      throw InvalidAmountException('amount must be more than zero, got $amount');
    }
    if (amount > balance) {
      throw InsufficientBalanceException(balance, amount);
    }
    balance -= amount;
    print('$owner withdrew Rs $amount, balance Rs $balance');
  }
}

The caller catches each type by name and can read its fields:

dart
try {
  acc.withdraw(amount);
} on InsufficientBalanceException catch (e) {
  print('Declined: you need Rs ${e.shortBy} more');
} on InvalidAmountException catch (e) {
  print('Declined: ${e.message}');
}

Code Examples

Example 1: A Bank Account With Custom Exceptions

dart
// (the two exception classes and Account from above)

void main() {
  var acc = Account('Sara', 3000);
  for (var amount in [1000.0, 0.0, 5000.0, 2000.0]) {
    try {
      acc.withdraw(amount);
    } on InsufficientBalanceException catch (e) {
      print('Declined: you need Rs ${e.shortBy} more');
    } on InvalidAmountException catch (e) {
      print('Declined: ${e.message}');
    }
  }

  try {
    acc.withdraw(10000);
  } catch (e) {
    print(e);
  }
}

Output

code
Sara withdrew Rs 1000.0, balance Rs 2000.0
Declined: amount must be more than zero, got 0.0
Declined: you need Rs 3000.0 more
Sara withdrew Rs 2000.0, balance Rs 0.0
InsufficientBalanceException: requested Rs 10000.0, balance Rs 0.0 (short by Rs 10000.0)

The last print(e) uses the overridden toString(), a clear message ready for a log.


Common Beginner Mistakes

1. Forgetting to override toString()

dart
class NoToString implements Exception {
  final String message;
  NoToString(this.message);
}

try {
  throw NoToString('Oops');
} catch (e) {
  print(e);
}

Output

code
Instance of 'NoToString'

The message is lost in the output. Override toString().

2. Throwing the class instead of an object

dart
class AgeException implements Exception {}

throw AgeException;
code
Unhandled exception:
AgeException

It looks almost right, but this throws the type itself, not an exception object, so on AgeException won't catch it. Write throw AgeException(); with brackets.

3. Not implementing Exception: Dart can throw any object, so class MyError {} can be thrown, but on Exception won't catch it, and it doesn't signal "this is an error to handle". Always write implements Exception.


Assignment

Build a student registration system with your own exceptions.

  1. Create InvalidAgeException implements Exception with a field int age and a toString() that says the age and the allowed range (5–100).
  2. Create DuplicateStudentException implements Exception with a field String name.
  3. Create a class School with a List<String> students field and a method void register(String name, int age) that:
    • throws InvalidAgeException if age < 5 or age > 100,
    • throws DuplicateStudentException if name is already in the list,
    • otherwise adds the name and prints Registered <name>.
  4. In main, try to register: ('Ali', 12), ('Sara', 3), ('Ali', 14), ('Zara', 9). Catch each exception type separately and print a friendly message.

Expected output (your wording may differ):

code
Registered Ali
Cannot register Sara: age 3 is outside 5–100
Cannot register Ali: already registered
Registered Zara

Practice Questions

  1. What must a class do to be a proper Dart exception?
  2. Why override toString() in an exception class?
  3. What's the difference between throw MyException; and throw MyException();?
  4. How do you read an exception's field in a catch?
  5. Give one advantage of a custom exception over StateError('...').

Practice Answers

  1. implements Exception.
  2. So print(e) shows a useful message instead of Instance of '...'.
  3. The first throws the type itself; the second throws an exception object, which is the correct way.
  4. Use on MyException catch (e), then e.fieldName.
  5. It can carry specific fields (like shortBy) and be caught by its exact name.

Key Takeaways

  • A custom exception is a class that implements Exception.
  • Give it fields describing the problem, and override toString().
  • throw MyException(...), with brackets, to create the object.
  • Catch it precisely with on MyException catch (e) and use its fields.