Back to quest
Control Flow & FunctionsLevel 22 / 32

Exception Handling

Try, Catch, Finally, and Throwing errors

Sometimes code fails—parsing an invalid number, losing internet connection, or reading a missing file. Exception handling lets your app recover from these errors instead of crashing.

1. Try, Catch, Stack Trace

When catching an error, you often want to know "where" it happened. Dart gives you a second parameter in catch for the stack trace.

Debugging Errors

example.dart
1try {
2 List<int> list = [1, 2, 3];
3 print(list[10]); // Crash!
4} catch (e, stackTrace) {
5 print('Error: $e');
6 print('Stack: $stackTrace');
7}

HintThe stack trace prints the chain of function calls leading to the error, which is vital for debugging complex apps.

2. Custom Exceptions

You are not limited to Dart built-in errors. You can create your own to represent specific business logic failures.

Defining Exceptions

example.dart
1class InsufficientFundsException implements Exception {
2 final String message;
3 InsufficientFundsException(this.message);
4
5 @override
6 String toString() => 'Error: $message';
7}
8 
9void withdraw(double amount) {
10 if (amount > 100) {
11 throw InsufficientFundsException('You only have $100');
12 }
13}
14 
15void main() {
16 try {
17 withdraw(500);
18 } on InsufficientFundsException catch (e) {
19 print(e); // Error: You only have $100
20 }
21}

HintImplementing Exception allows you to catch this specific error type using on.

3. Rethrowing Exceptions

Sometimes you want to catch an error just to log it (e.g., to an analytics server), but you still want the app to know an error occurred.

Log and Pass

example.dart
1void dataFetcher() {
2 try {
3 // Fetch data...
4 throw Exception('Network Failed');
5 } catch (e) {
6 print('Logging error to server...');
7 rethrow; // Pass the error up to the caller
8 }
9}
10 
11void main() {
12 try {
13 dataFetcher();
14 } catch (e) {
15 print('Main UI: Show error dialog');
16 }
17}

Hintrethrow preserves the original stack trace. If you just threw e again, you would lose the history of where the original error came from.

Loot collected

Key takeaways
  • Use try-catch to prevent your app from crashing.
  • Use finally for cleanup code (like closing files) that must always run.
  • Use on ExceptionType to handle specific errors.
  • You can throw your own exceptions to enforce rules.

Side quests

Practice exercises

1

Exercise 1: Safe Division

Write a try-catch block that attempts to divide by zero and catches the error.

Reveal solution
solution.dart
1try { print(10 ~/ 0); } catch(e) { print('Error'); }
2

Exercise 2: Custom Error

Throw an exception if a user age is negative.

Reveal solution
solution.dart
1if (age < 0) throw Exception('Invalid age');
Party chat

Comments