Dart Custom Exceptions
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.