In Dart, try, catch, and finally are used together to handle exceptions and ensure your program runs smoothly even when errors occur. Hereβs how each works:
tryblock:
This contains the code that might throw an exception. You put any risky operation here, like file reading, network calls, or division by zero.
try {
int result = 12 ~/ 0; // Might throw an exception
print(result);
}
catch block:
This block handles the exception if it occurs. You can access the exception object to see what went wrong. You can also get the stack trace for debugging.
catch (e, stackTrace) {
print("Error: $e");
print("Stack trace: $stackTrace");
}
You can also catch specific types of exceptions using on:
try {
int num = int.parse("abc");
} on FormatException catch (e) {
print("Invalid number: $e");
}
finally block:
This block always executes, whether an exception occurs or not. Itβs useful for cleanup tasks, like closing files or network connections.
finally {
print("This block always runs");
}
Complete example:
void main() {
try {
int result = 12 ~/ 0;
print(result);
} catch (e) {
print("An error occurred: $e");
} finally {
print("Cleaning up resources...");
}
}
Output:
An error occurred: IntegerDivisionByZeroException
Cleaning up resources...
Practical Use:
I often use try-catch-finally when fetching data from APIs or reading files. For instance, if the network fails, I catch the exception to show a user-friendly message, and the finally block ensures resources like loading indicators are removed.
Challenges:
- Forgetting
catchfor specific exceptions can make debugging harder. - Using
finallyfor critical operations ensures they run even if the program throws an error.
This structure makes Dart programs robust, safe, and user-friendly, especially when working with unpredictable operations like I/O or network requests.
