What are Exceptions?
An exception is an error that occurs during program execution. Without handling, exceptions crash the program. Dart provides try-catch-finally to gracefully handle errors and keep programs running.
Try-Catch
try {
int result = 10 ~/ 0; // throws IntegerDivisionByZeroException
print(result);
} catch (e) {
print('Caught: $e');
}
// Program continues...
on Clause
Use on to catch specific exception types:
try {
var list = [1, 2, 3];
print(list[10]); // RangeError
} on RangeError catch (e) {
print('Range error: $${e.message}');
} on FormatException catch (e) {
print('Format error: $e');
} catch (e, stackTrace) {
print('Unknown error: $e');
print(stackTrace);
}
Finally
The finally block always runs — whether or not an exception occurred. Use it for cleanup (closing files, releasing resources):
void readFile() {
print('Opening file...');
try {
throw FormatException('Invalid data');
} catch (e) {
print('Error: $e');
} finally {
print('Closing file...'); // always runs
}
}
Throwing Exceptions
void validateAge(int age) {
if (age < 0) throw ArgumentError('Age cannot be negative: $age');
if (age > 150) throw RangeError('Unrealistic age: $age');
print('Valid age: $age');
}
void main() {
try {
validateAge(-5);
} on ArgumentError catch (e) {
print('Invalid argument: $${e.message}');
}
}
Custom Exceptions
class InsufficientFundsException implements Exception {
final double amount;
InsufficientFundsException(this.amount);
@override
String toString() => 'InsufficientFundsException: Need \$$amount more.';
}
class BankAccount {
double balance;
BankAccount(this.balance);
void withdraw(double amount) {
if (amount > balance) throw InsufficientFundsException(amount - balance);
balance -= amount;
}
}
void main() {
var account = BankAccount(100.0);
try {
account.withdraw(150.0);
} on InsufficientFundsException catch (e) {
print(e); // InsufficientFundsException: Need $50.0 more.
}
}
Output:Invalid argument: Age cannot be negative: -5
InsufficientFundsException: Need $50.0 more.
🧠 Quiz
1. Which block always runs regardless of exceptions?
- A) catch
- B) try
- C) finally ✅
- D) on
2. How do you create a custom exception in Dart?
- A) extends Exception
- B) implements Exception ✅
- C) mixin Exception
- D) with Exception
Summary
Use try-catch to handle exceptions. Use on ExceptionType to catch specific types. The finally block always runs for cleanup. Throw exceptions with throw. Create custom exceptions by implementing the Exception interface and overriding toString().