Error vs Exception
- Dart course
- Intermediate
- Lesson 101/116
- 5 min
Learn the difference between Error and Exception.
Error vs Exception
Dart has two kinds of problems: Error and Exception. They must not be confused; telling them apart is the basis of solid error handling.
Error (e.g. StateError, RangeError) is a programmer mistake; it is unrecoverable and should not be caught. You fix the code instead.
Exception (e.g. FormatException, TimeoutException) is a runtime condition; it is recoverable and caught with try/catch.
Catching Error
Catching an Error with try/catch is generally a bad practice. An Error is a bug you must fix in your code; catching it hides the bug.
Instead catch Exception: try { ... } on Exception catch (e) { ... }. This handles expected runtime conditions.
If your program throws an Error, fix the source; do not try to catch it.
Practice Catch FormatException
Write int parseAge(String s) => int.parse(s);. In main call parseAge('abc'); catch it with on FormatException catch (e) and print print('invalid age').
Starter code
// Define the parseAge function
void main() {
// call parseAge('abc'), catch FormatException
}Sample solution
int parseAge(String s) => int.parse(s);
void main() {
try {
parseAge('abc');
} on FormatException catch (e) {
print('invalid age');
}
}Expected output
invalid age
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 NetworkError class
class NetworkError extends ____ { final String host; NetworkError(this.host); }
class NetworkError extends Error { final String host; NetworkError(this.host); }
Explanation: NetworkError is an Error subclass.
2 Which is an Error subclass?
- FormatException
- TimeoutException
- FileSystemException
- StateError Correct answer
Explanation: StateError extends Error. The others are Exception subclasses.
3 Error vs Exception comparison
| Term | Meaning |
|---|---|
Error |
Programmer mistake |
Exception |
Runtime condition |
StateError |
Error subclass |
FormatException |
Exception subclass |