Learn Dart Β· 9/12

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 to Exception or Error.


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

  1. try: The dangerous code goes here.
  2. catch: If something explodes in the try block, code execution jumps here immediately.
dart
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.

dart
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.

dart
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.
dart
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.

dart
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

dart
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.

dart
// 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

  1. Errors are for when the code is broken (fix the code).
  2. Exceptions are for when the runtime environment behaves unexpectedly (handle the user experience).
  3. Use try for risky code.
  4. Use on to catch specific issues.
  5. Use catch (e, s) to log unknown errors and stack traces.
  6. Use finally to clean up resources (close files, stop loading animations).
  7. 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

  1. Define a class named InvalidTransactionException that implements the built-in Exception interface. This class should have a final String property named errorMessage and a constructor to initialize it.

  2. Implement the processTransactions function. It takes one argument: a List<String> named transactions.

  3. Inside this function, create a local bool variable named isProcessing and initialize it to true to simulate the start of an operation.

  4. Use a try-on-finally block to wrap the core logic:

    • try block: Iterate through the transactions list. For each string:
      • Attempt to parse it into a double.
      • If the parsed amount is negative, throw an instance of your InvalidTransactionException, passing a relevant error message to its constructor.
      • If the amount is valid (non-negative), add it to a list of processed transactions.
    • on clauses: Create two separate on clauses 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 immediately rethrow the exception to be handled by the caller.
    • finally block: This block must always execute and set the isProcessing variable back to false, ensuring the system state is cleaned up.
  5. The processTransactions function should return the list of successfully processed, valid transactions.

  6. In the main function, call processTransactions inside a try-catch block to handle the re-thrown InvalidTransactionException. If this exception is caught, the catch block 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.

dart

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.