Error Handling: Dealing with the Unexpected
6 min read
Welcome to the chaotic reality of software development.
In a perfect world, users always enter valid email addresses, APIs never time out, and files are always exactly where you left them. In the real world, however, users try to upload 5TB video files as profile pictures, the internet disconnects when the microwave runs, and servers catch fire.
If you don't handle these situations, your Dart application crashes. The screen freezes, the app closes, and your user uninstalls it.
Error Handling is the art of writing code that says, "I hope this works, but if it doesn't, here is Plan B."
1. Exceptions vs Errors in Dart π₯
Before we start catching things, we need to know what we are catching. In Dart, the distinction between an Exception and an Error is specific and important for how you structure your logic.
The Problem
You write a function to divide a number. The user inputs 0.
Mathematically, dividing by zero is undefined. The CPU cannot process this. If the program continues blindly, it corrupts the state or halts execution entirely.
The Solution: The Crash Report
Dart stops the program and reports an "IntegerDivisionByZeroException".
Technical Definition
In Dart, both Exceptions and Errors are objects that can be thrown. They both act as interruptions to the normal flow of the program.
ποΈ Exceptions (Exception)
An Exception is an event that hinders the execution of a program but is generally meant to be caught and handled. These are often external issues or valid state checks.
- Nature: Recoverable.
- Examples:
FormatException(parsing "abc" to an integer),IOException(file not found),TimeoutException. - Action: You should catch these and show a nice message to the user.
π£ Errors (Error)
An Error represents a program failure. These usually indicate that the programmer made a mistake in the logic.
- Nature: Unrecoverable (usually).
- Examples:
OutOfMemoryError(you used all the RAM),StackOverflowError(infinite recursion),ArgumentError. - Action: You generally do not catch these. If your app runs out of memory, catching it won't magically create more RAM. You fix the code that caused the leak.
Funny Fact: You can technically
throw "I am a string";in Dart. Dart allows you to throw any non-null object. However, please don't do this. If you throw a String at a coworker in the office, HR gets involved. If you throw a String in code, the linter gets mad. Stick toExceptionorError.
2. Using Try, Catch, and Finally Blocks πΈοΈ
Now that we know things can break, let's look at the syntax for safety nets.
The Problem
When an exception occurs, it "bubbles up" the call stack. If nothing catches it, it reaches the main() function, prints a red wall of text to the console, and kills the process.
The Solution: try-catch
We wrap "risky" code in a protection block.
Basic Syntax
try: The dangerous code goes here.catch: If something explodes in thetryblock, code execution jumps here immediately.
void main() {
print("1. Attempting to parse data...");
try {
String input = "not_a_number";
// This line throws a FormatException
int number = int.parse(input);
// This line is SKIPPED because of the crash above π
print("2. Success! The number is $number");
} catch (e) {
// 'e' is the exception object
print("3. Oops! Something went wrong: $e");
}
print("4. App continues running normally.");
}Industry Standard: The on Keyword π―
In professional Dart development, simply writing catch (e) is often considered lazy because it catches everything. Usually, you want to handle specific problems differently.
- If the internet is down -> Show "Check Connection".
- If the login is wrong -> Show "Invalid Password".
Use the on keyword to filter exception types.
void main() {
try {
var result = 100 ~/ 0; // Integer division by zero
} on UnsupportedError {
print("π Math Error: You cannot divide by zero.");
} on FormatException {
print("π Format Error: Bad input format.");
} catch (e) {
// The "Buckets": Catches anything not listed above
print("π Unknown error: $e");
}
}Getting the Stack Trace π΅οΈββοΈ
Knowing what happened is good (e). Knowing where it happened is better. The second parameter in a catch block gives you the Stack Trace.
try {
// Risky code
} catch (e, stackTrace) {
print("Error: $e");
// In production, send this stackTrace to tools like Sentry or Firebase Crashlytics
print("Line of crime: $stackTrace");
}The finally Block π§Ή
The finally block runs no matter what. Whether the code succeeded or failed, finally executes.
This is critical for "Cleanup" tasks:
- Closing a file stream.
- Closing a database connection.
- Stopping a loading spinner in the UI.
void performServerRequest() {
print("π΅ Loading spinner ON");
try {
// Imagine this is a network request that fails
throw Exception("Server is on fire π₯");
} catch (e) {
print("π΄ Error handled: $e");
} finally {
// This runs even though there was an error!
print("π΅ Loading spinner OFF");
}
}The rethrow Keyword π
Sometimes you catch an error just to log it, but you still want the app to crash or the UI to handle the alert. You can process the error and then throw it again using rethrow.
void login() {
try {
// Attempt login
} catch (e) {
print("Log error to database internal system...");
rethrow; // Pass the error up to the UI layer to show a popup
}
}3. Throwing and Creating Custom Exceptions π₯
Sometimes, the standard Dart exceptions aren't specific enough. If you are building a banking app, FormatException doesn't quite capture the emotion of "Insufficient Funds".
The Problem
Your business logic has specific rules (e.g., "Age cannot be negative"). If these rules are violated, you need a way to stop execution that is recognizable to other developers using your code.
The Solution: throw and Custom Classes
You can manually trigger an interruption.
Throwing a Standard Exception
void setAge(int age) {
if (age < 0) {
throw ArgumentError("Age cannot be negative! You are not a time traveler.");
}
print("Age set to $age");
}Creating Custom Exceptions
To create your own, simply create a class. It is standard practice to implement the Exception interface.
// 1. Define the custom exception
class InsufficientFundsException implements Exception {
final double currentBalance;
final double attemptedAmount;
InsufficientFundsException(this.currentBalance, this.attemptedAmount);
@override
String toString() {
return "InsufficientFundsException: Cannot withdraw \$$attemptedAmount. You only have \$$currentBalance.";
}
}
// 2. Use it in business logic
void withdrawMoney(double amount) {
double balance = 50.00;
if (amount > balance) {
// Throw your custom object
throw InsufficientFundsException(balance, amount);
}
print("Withdrew \$$amount");
}
// 3. Handle it
void main() {
try {
withdrawMoney(100.00);
} on InsufficientFundsException catch (e) {
// Now we can access specific properties of our custom error!
print("Transaction Failed: ${e.toString()}");
}
}Industry Best Practice: Interfaces
Dart Docs recommend that your custom exceptions implement Exception so that try-catch blocks recognize them easily.
π§ͺ Practical Summary
- Errors are for when the code is broken (fix the code).
- Exceptions are for when the runtime environment behaves unexpectedly (handle the user experience).
- Use
tryfor risky code. - Use
onto catch specific issues. - Use
catch (e, s)to log unknown errors and stack traces. - Use
finallyto clean up resources (close files, stop loading animations). - Define Custom Exceptions when your app has specific business rules that can be violated.
π References & Further Reading
Challenge
Your task is to build a robust data processing function in Dart that correctly handles various types of runtime issues using try, on, finally, rethrow, and custom exceptions.
Instructions
Define a class named
InvalidTransactionExceptionthat implements the built-inExceptioninterface. This class should have afinal Stringproperty namederrorMessageand a constructor to initialize it.Implement the
processTransactionsfunction. It takes one argument: aList<String>namedtransactions.Inside this function, create a local
boolvariable namedisProcessingand initialize it totrueto simulate the start of an operation.Use a
try-on-finallyblock to wrap the core logic:tryblock: Iterate through thetransactionslist. For each string:- Attempt to parse it into a
double. - If the parsed amount is negative,
throwan instance of yourInvalidTransactionException, passing a relevant error message to its constructor. - If the amount is valid (non-negative), add it to a list of processed transactions.
- Attempt to parse it into a
onclauses: Create two separateonclauses to handle specific exceptions:- One for
FormatException. When caught, this block should do nothing except prepare for the next iteration (i.e., you can leave it empty or add a print statement for debugging, but it should not stop the loop). - One for your custom
InvalidTransactionException. When caught, it should immediatelyrethrowthe exception to be handled by the caller.
- One for
finallyblock: This block must always execute and set theisProcessingvariable back tofalse, ensuring the system state is cleaned up.
The
processTransactionsfunction should return the list of successfully processed, valid transactions.In the
mainfunction, callprocessTransactionsinside atry-catchblock to handle the re-thrownInvalidTransactionException. If this exception is caught, thecatchblock should do nothing.
Expected result
Your code should correctly define the InvalidTransactionException class implementing Exception.
The processTransactions function must contain a try-on-finally block. Inside the try block, it should iterate through the list, parsing strings to doubles. It must throw an InvalidTransactionException when a negative number is encountered. It must include an on FormatException clause and another on InvalidTransactionException clause that uses the rethrow keyword. The finally block must unconditionally set the isProcessing flag to false.
The main function's logic should be wrapped in a try-catch block that calls processTransactions and is capable of catching the re-thrown InvalidTransactionException.