Sub topic 13
Handling Errors with Exceptions
This chapter assumes that you know Dart variables, functions, classes, and basic control flow. You should also be comfortable running a Dart program from a terminal.
Why exceptions matter
An exception is an object that describes an unusual condition during program execution. For example, a program might receive invalid input, fail to open a file, or receive an unexpected response from a service.
Dart exceptions are unchecked. The compiler does not require a function to declare every exception it might throw. The code that knows how to recover should catch the exception. Code that cannot recover should let it move to a higher-level handler.
Use throw to signal failure:
throw FormatException('Age must be a number');Dart can throw any non-null object, but prefer Exception types such as FormatException, ArgumentError, or StateError. These types communicate what went wrong.
Catching exceptions
Put risky code inside a try block. Use on when you want to handle a specific exception type. Use catch to receive the exception object and, optionally, its stack trace.
A stack trace records the calls that led to the failure. It is useful when logging or debugging.
int parsePositiveAge(String text) {
final age = int.tryParse(text);
if (age == null) {
throw FormatException('Age must be a whole number');
}
if (age < 0) {
throw ArgumentError.value(age, 'age', 'must not be negative');
}
return age;
}
void main() {
final inputs = ['36', 'unknown', '-2'];
for (final input in inputs) {
try {
final age = parsePositiveAge(input);
print('$input is valid: $age');
} on FormatException catch (error, stackTrace) {
print('Invalid format: $error');
print('Trace available: ${stackTrace.isNotEmpty}');
} on ArgumentError catch (error) {
print('Invalid value: $error');
} catch (error, stackTrace) {
print('Unexpected failure: $error');
print(stackTrace);
} finally {
print('Finished processing "$input"');
}
}
}The finally block runs whether the try block succeeds or throws. Use it for cleanup, such as closing a resource or resetting a loading flag.
Rethrowing exceptions
Sometimes a function can add useful context but cannot recover. In that case, catch the exception, record the context, and use rethrow:
void readConfiguration() {
try {
// Read and decode configuration here.
throw StateError('configuration is missing');
} catch (error, stackTrace) {
print('Configuration loading failed: $error');
print(stackTrace);
rethrow;
}
}rethrow preserves the original stack trace. Throwing error again can make the trace point to the wrong location.
Exception flow
Common errors
- Catching
Exceptionwhen a more specific type is available can hide programming mistakes. - Omitting
finallycan leave resources open after a failure. - Returning a fake success value can make the original problem harder to detect.
- Logging sensitive input or stack traces in production can expose private data.
Exercise
When should you use rethrow instead of throw error inside a catch block?
Show answer
Use rethrow when the current function cannot recover but needs to add context, because rethrow preserves the original stack trace.