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.
Handle errors gracefully with try, catch, and finally
Passing the Quiz & Exercises is mandatory to earn FX and proceed. If you fail, try again to gain the required FX, then the Proceed button will become available.
You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.
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
Real apps encounter failures such as network errors, missing files, and invalid input. Exception handling lets your app recover gracefully instead of crashing.
1// ── Basic try / catch ──2void parseNumber() {3try {4int result = int.parse('abc'); // throws FormatException5print(result);6} catch (e) {7print('Error: $e'); // Error: FormatException: ...8}9}1011// ── Catch specific exceptions ──12void readData() {13try {14throw FormatException('Bad data');15} on FormatException catch (e) {16print('Format error: $e');17} on Exception catch (e) {18print('General error: $e');19} catch (e) {20print('Unknown: $e'); // catches anything21}22}2324// ── finally (always runs) ──25Future<void> fetchUser() async {26try {27final data = await api.getUser();28print(data);29} catch (e) {30print('Failed: $e');31} finally {32print('Request complete'); // runs whether or not error occurred33}34}
1// ── Throw your own exceptions ──2void validateAge(int age) {3if (age < 0 || age > 150) {4throw ArgumentError('Invalid age: $age');5}6}78// ── Custom Exception class ──9class ApiException implements Exception {10final String message;11final int statusCode;12ApiException(this.message, this.statusCode);1314@override15String toString() => 'ApiException [$statusCode]: $message';16}1718// ── Using in Flutter ──19Future<void> loadProfile() async {20try {21final user = await fetchFromServer();22setState(() => _user = user);23} catch (e) {24setState(() => _error = 'Failed to load profile. Try again.');25}26}
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.
Treat errors by category instead of one generic catch message:
This classification improves both user experience and debugging speed.
Handle errors gracefully with try, catch, and finally. This lesson adds one more building block for creating stable and user-friendly Flutter apps.
Build confidence with basics first; speed comes later.
After reading, rewrite the concept in your own words and apply it in a tiny runnable sample.
Each lesson becomes useful when you connect concept, implementation, and real-user outcome together.
The finally block always executes, even if an exception is thrown and caught. Use it for cleanup like closing connections.
Dart uses "on ExceptionType catch (e)" to catch specific exception types. You can chain multiple on-catch blocks.
throw is used to throw any exception or error. Example: throw ArgumentError("Invalid value");
Custom exceptions (implementing Exception) let you carry typed error info and catch them specifically with "on CustomException catch (e)".
Something seems incorrect, unclear, or missing? Let us know.
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