Learn/Dart for Flutter/Exception Handling

Exception Handling

Handle errors gracefully with try, catch, and finally

5 min~4 min read+30 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Error Taxonomy For Better Handling
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Exception Handling in Dart

Real apps encounter failures such as network errors, missing files, and invalid input. Exception handling lets your app recover gracefully instead of crashing.

dart
1// ── Basic try / catch ──
2void parseNumber() {
3 try {
4 int result = int.parse('abc'); // throws FormatException
5 print(result);
6 } catch (e) {
7 print('Error: $e'); // Error: FormatException: ...
8 }
9}
10
11// ── Catch specific exceptions ──
12void readData() {
13 try {
14 throw FormatException('Bad data');
15 } on FormatException catch (e) {
16 print('Format error: $e');
17 } on Exception catch (e) {
18 print('General error: $e');
19 } catch (e) {
20 print('Unknown: $e'); // catches anything
21 }
22}
23
24// ── finally (always runs) ──
25Future<void> fetchUser() async {
26 try {
27 final data = await api.getUser();
28 print(data);
29 } catch (e) {
30 print('Failed: $e');
31 } finally {
32 print('Request complete'); // runs whether or not error occurred
33 }
34}
dart
1// ── Throw your own exceptions ──
2void validateAge(int age) {
3 if (age < 0 || age > 150) {
4 throw ArgumentError('Invalid age: $age');
5 }
6}
7
8// ── Custom Exception class ──
9class ApiException implements Exception {
10 final String message;
11 final int statusCode;
12 ApiException(this.message, this.statusCode);
13
14 @override
15 String toString() => 'ApiException [$statusCode]: $message';
16}
17
18// ── Using in Flutter ──
19Future<void> loadProfile() async {
20 try {
21 final user = await fetchFromServer();
22 setState(() => _user = user);
23 } catch (e) {
24 setState(() => _error = 'Failed to load profile. Try again.');
25 }
26}

Always Handle Network Exceptions

💡 Always Handle Network Exceptions

Every API call should be inside a try/catch. Users should see a helpful error message, not a crash. Use `setState` to show error state in Flutter.

Error Taxonomy For Better Handling

Treat errors by category instead of one generic catch message:

  • Validation errors: user input issues (show field-level guidance)
  • Network errors: timeout/offline/server unavailable (offer retry)
  • Authorization errors: session expired or permission denied (re-auth flow)
  • Unknown errors: log details and show safe fallback message

This classification improves both user experience and debugging speed.

Production-Ready Exception Handling

  • Catch specific exceptions before generic catch blocks.
  • Log technical details, but show user-friendly messages in UI.
  • Use finally for cleanup that must always run.
  • Add retry actions for transient failures.

This Lesson In Simple Words

Handle errors gracefully with try, catch, and finally. This lesson adds one more building block for creating stable and user-friendly Flutter apps.

Your level focus

Build confidence with basics first; speed comes later.

One practical habit

After reading, rewrite the concept in your own words and apply it in a tiny runnable sample.

Deep Understanding Guide

Why this lesson matters

Each lesson becomes useful when you connect concept, implementation, and real-user outcome together.

Study flow for better retention

  1. Read one section, run one tiny example, then explain the idea in your own words.
  2. Use a simple cycle: understand, implement, test, and explain.
  3. If you can teach it in 45 seconds without notes, you understood it.

Common Mistakes To Avoid

  • Moving forward without checking whether the current concept is truly clear.
  • Copying code exactly without experimenting with small changes.
  • Skipping edge cases and only testing happy-path behavior.
  • Assuming one pattern works for every scenario without trade-off analysis.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build one tiny example from memory after finishing this lesson.
  • Write one paragraph about where this concept fits in a real app.
  • Create one failure scenario and verify your app handles it safely.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "Which block always runs regardless of exceptions?".

Quick Glossary

  • validation: Checks that confirm input is correct before processing.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Lesson Completion Checklist

  • I can explain "Exception Handling" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Moving forward without checking whether the current concept is truly clear.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

Which block always runs regardless of exceptions?

The finally block always executes, even if an exception is thrown and caught. Use it for cleanup like closing connections.

What is the Dart syntax to catch a specific exception type?

Dart uses "on ExceptionType catch (e)" to catch specific exception types. You can chain multiple on-catch blocks.

What keyword throws an exception manually in Dart?

throw is used to throw any exception or error. Example: throw ArgumentError("Invalid value");

What is the purpose of a custom Exception class in Dart?

Custom exceptions (implementing Exception) let you carry typed error info and catch them specifically with "on CustomException catch (e)".

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue