Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart Custom Exceptions


Share

Dart Custom Exceptions

Dart has many built-in exceptions, like FormatException.

But often, the problem is special to your own program, like "not enough money in the account".

For this, you can create a custom exception, which is your own exception class.

A custom exception is a normal class that implements the Exception interface:

Example

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

  @override
  String toString() => 'InsufficientFundsException: $message';
}

void main() {
  try {
    throw InsufficientFundsException('Not enough money in the account');
  } catch (e) {
    print(e);
  }
}
Try it Yourself »

Result:

InsufficientFundsException: Not enough money in the account

By convention, the name of an exception class ends with Exception.


Why toString() Matters

When you print an object, Dart calls its toString() method.

If your exception class does not have its own toString(), the message is not very helpful:

Example

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

void main() {
  try {
    throw InsufficientFundsException('Not enough money in the account');
  } catch (e) {
    print(e);
  }
}
Try it Yourself »

Result:

Instance of 'InsufficientFundsException'

The text from toString() is also what Dart shows when nobody catches the exception and the program stops:

Example

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

  @override
  String toString() => 'InsufficientFundsException: $message';
}

void main() {
  throw InsufficientFundsException('Not enough money in the account');
}
Try it Yourself »

Result:

Unhandled exception:
InsufficientFundsException: Not enough money in the account

Tip: Always add a toString() method that explains what went wrong.



Catch Your Own Exception Type

A custom exception can have extra fields with details about the problem.

Use on with your class name to catch only your exception, and read its fields:

Example

class InsufficientFundsException implements Exception {
  final double balance;
  final double amount;
  InsufficientFundsException(this.balance, this.amount);

  @override
  String toString() =>
      'InsufficientFundsException: tried to take $amount, but the balance is $balance';
}

class BankAccount {
  double balance = 0;

  void deposit(double amount) {
    balance += amount;
  }

  void withdraw(double amount) {
    if (amount > balance) {
      throw InsufficientFundsException(balance, amount);
    }
    balance -= amount;
  }
}

void main() {
  var account = BankAccount();
  account.deposit(100);

  try {
    account.withdraw(30);
    print('Balance: ${account.balance}');
    account.withdraw(500);
    print('Balance: ${account.balance}');
  } on InsufficientFundsException catch (e) {
    print(e);
    print('You need ${e.amount - e.balance} more');
  }
}
Try it Yourself »

Result:

Balance: 70.0
InsufficientFundsException: tried to take 500.0, but the balance is 70.0
You need 430.0 more

The second print('Balance: ...') never runs, because withdraw(500) throws the exception first.

Inside the on block, Dart knows that e is an InsufficientFundsException, so you can use e.amount and e.balance.


A Family of Exceptions

A program often has several custom exceptions that belong together.

Give them a common parent class.

Then you can catch one exact type, or the whole family with the parent type:

Example

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

  @override
  String toString() => '$runtimeType: $message';
}

class OutOfStockException extends OrderException {
  OutOfStockException(String product) : super('$product is out of stock');
}

class InvalidQuantityException extends OrderException {
  InvalidQuantityException(int quantity) : super('$quantity is not a valid quantity');
}

void order(String product, int quantity) {
  if (quantity <= 0) {
    throw InvalidQuantityException(quantity);
  }
  if (product == 'Mango') {
    throw OutOfStockException(product);
  }
  print('Ordered $quantity $product');
}

void main() {
  var orders = [('Apple', 3), ('Mango', 2), ('Banana', 0)];

  for (var (product, quantity) in orders) {
    try {
      order(product, quantity);
    } on OutOfStockException catch (e) {
      print('Sorry! $e');
    } on OrderException catch (e) {
      print('Order failed. $e');
    }
  }
}
Try it Yourself »

Result:

Ordered 3 Apple
Sorry! OutOfStockException: Mango is out of stock
Order failed. InvalidQuantityException: 0 is not a valid quantity

OutOfStockException has its own on block.

InvalidQuantityException does not, so it is caught by on OrderException, its parent class.

Put the most specific types first, because Dart uses the first on block that matches.


Validate Input

Custom exceptions are a good way to check input in one place, and handle the problem in another place:

Example

class InvalidAgeException implements Exception {
  final int age;
  InvalidAgeException(this.age);

  @override
  String toString() => 'InvalidAgeException: $age is not a valid age';
}

int checkAge(int age) {
  if (age < 0 || age > 150) {
    throw InvalidAgeException(age);
  }
  return age;
}

void main() {
  for (var age in [25, -3, 200]) {
    try {
      print('Age ${checkAge(age)} is valid');
    } on InvalidAgeException catch (e) {
      print(e);
    }
  }
}
Try it Yourself »

Result:

Age 25 is valid
InvalidAgeException: -3 is not a valid age
InvalidAgeException: 200 is not a valid age

Note: Your class should implement Exception, not extend Error.

As you learned in the Exceptions chapter, an Error means a bug in the code, and an Exception means a problem that the program can handle.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.