In Dart, exception handling is done using try-catch blocks, optionally with a finally block. Exception handling is essential to make programs robust and prevent crashes when unexpected errors occur, like invalid input, file not found, or network failure.
- Basic try-catch:
You wrap the code that might throw an exception in atryblock and handle the exception in acatchblock.
filename.dart
void main() {
try {
int result = 12 ~/ 0; // Integer division by zero
print(result);
} catch (e) {
print("An error occurred: $e");
}
}
Here, ~/ is integer division. Dividing by zero throws an exception, which is caught in the catch block.
- Catching the Stack Trace:
You can also capture the stack trace to debug where the error happened:
filename.dart
try {
int result = 12 ~/ 0;
} catch (e, stackTrace) {
print("Error: $e");
print("Stack trace: $stackTrace");
}
- Using finally:
Thefinallyblock executes regardless of whether an exception occurred, which is useful for cleanup tasks, like closing files or database connections.
filename.dart
try {
int result = 12 ~/ 0;
} catch (e) {
print("Error occurred: $e");
} finally {
print("This always runs");
}
- Practical Use:
In projects, I often handle exceptions when making network requests or parsing JSON data, because APIs can fail or return unexpected data. Handling exceptions prevents the app from crashing and allows me to show meaningful error messages to users. - Challenges:
- Overusing generic
catch (e)can hide the type of error. Sometimes itβs better to catch specific exceptions likeFormatExceptionorIOException. - Forgetting to handle exceptions in asynchronous code (
asyncfunctions) can lead to unhandled Future errors.
filename.dart
try {
await fetchData(); // async function
} catch (e) {
print("Network error: $e");
}
- Alternative:
- Use
onkeyword to catch specific exception types:
filename.dart
try {
int result = int.parse("abc");
} on FormatException catch (e) {
print("Invalid number: $e");
}
Exception handling in Dart is flexible, safe, and combines well with asynchronous programming to make applications stable and user-friendly.
