Error Handling Strategies
Exceptions vs error values, checked vs unchecked errors, failing fast, and reliable cleanup with finally, defer and RAII.
What is it?
Things go wrong: files are missing, networks drop, input is malformed. Languages offer two main ways to report failure:
- Exceptions (Python, Java, JavaScript, C#): a failing function throws, normal execution stops, and control jumps up the call stack to the nearest matching catch/except. Code in between doesn't have to mention the error at all. - Error values (Go, Rust, C): a failing function returns the error as part of its result. Go returns (value, err); Rust returns Result<T, E>, which is either Ok(value) or Err(error). The caller must deal with it explicitly.
Java adds a split between checked exceptions (declared in the method signature, the compiler forces callers to handle them) and unchecked ones (any RuntimeException, no declaration needed).
Two principles apply in every language. Fail fast: detect bad input or state as early as possible and stop loudly, instead of carrying on with corrupt data. And always clean up: release files, locks and connections whether the code succeeded or failed, using finally, with, defer or RAII.
Explain like I'm 10
An exception is a fire alarm: when it goes off, everyone stops what they're doing and the building's fire plan takes over somewhere else. An error value is a note left on your desk saying 'the delivery failed': nothing stops, but you're expected to read it and decide what to do.
Examples
Exceptions with cleanup (Python)
import json
def load_config(path: str) -> dict:
try:
with open(path, encoding="utf-8") as file: # file closed automatically
return json.load(file)
except FileNotFoundError:
return {} # sensible default
except json.JSONDecodeError as error:
raise ValueError(f"Config {path} is not valid JSON: {error}") from errorErrors as values (Go and Rust)
// Go: errors are ordinary return values
func readPort(path string) (int, error) {
data, err := os.ReadFile(path)
if err != nil {
return 0, fmt.Errorf("reading %s: %w", path, err)
}
defer log.Println("done reading", path) // runs when the function returns
return strconv.Atoi(strings.TrimSpace(string(data)))
}
// Rust: Result<T, E> and the ? operator, which returns early on Err
// fn read_port(path: &str) -> Result<u16, Box<dyn std::error::Error>> {
// let text = std::fs::read_to_string(path)?;
// let port = text.trim().parse::<u16>()?;
// Ok(port)
// }Every failure point is visible in the code. Rust's ? keeps that explicitness while removing the repetitive if err != nil boilerplate.
Fail fast at the boundary (TypeScript)
function createUser(email: string, age: number) {
if (!email.includes("@")) {
throw new Error("Invalid email: " + email);
}
if (!Number.isInteger(age) || age < 0) {
throw new RangeError("Age must be a non-negative integer");
}
// From here on, the data is known to be valid.
return { email, age };
}How it works
When an exception is thrown, the runtime unwinds the stack: it pops frames one by one, running any finally blocks or destructors on the way, until it finds a handler whose type matches. If none matches, the program (or thread, or request) crashes with a stack trace.
Error values involve no special control flow. They're returned like any other value, so the type system can force callers to look at them. Rust's Result must be used (the compiler warns if you ignore it) and ? propagates it upward.
Cleanup mechanisms guarantee release of resources:
- try/finally (Java, JavaScript, Python): the finally block always runs. - Context managers / try-with-resources (with in Python, Java's try (var r = ...)): cleanup tied to a block. - defer (Go): schedule a call to run when the function returns. - RAII (C++, Rust): a resource is owned by an object, and the object's destructor (Rust's Drop) releases it when it goes out of scope.
Exception propagation (unwinding)
main() <- catch (ValueError) handles it here
load_app() <- no handler: finally blocks run, frame popped
load_config() <- raise ValueErrorWhy does it exist?
Before structured error handling, C programs checked return codes by hand and frequently forgot to, letting errors slip through silently. Exceptions made it impossible to ignore failure accidentally and separated error handling from the happy path. Error values came back (Go, Rust) because exceptions make control flow invisible: any line might jump away. Both approaches aim at the same goal: errors that can't be silently lost.
When to use it
Use exceptions (in exception-based languages) for conditions the immediate caller usually can't fix: I/O failure, invalid state, programmer errors. Use error values or a Result type for expected, recoverable outcomes that callers should always consider, like "not found" or "validation failed". Validate input where it enters the system. Wrap every resource in a cleanup construct.
When not to use it
Don't use exceptions for normal control flow (ending a loop, signalling "not found" in a hot path); they're slower and obscure intent. Don't catch exceptions you can't handle just to log and continue, and never swallow them with an empty catch. Don't catch the broadest type (Exception, Throwable) except at a top-level boundary such as a request handler.
Common mistakes
Empty catch blocks (
except: pass,catch (e) {}) that hide failures and leave the program in an unknown state.Catching overly broad exceptions (
except Exception,catch (Throwable t)) deep in the code and accidentally handling bugs as if they were expected errors.Ignoring a returned error (
value, _ := f()in Go) or calling.unwrap()everywhere in Rust.Forgetting cleanup on the error path, leaking file handles, locks or database connections.
Re-throwing a new error without the original cause, losing the stack trace needed for debugging.
Practice exercises
- Easy:
Write a function
parseAge(text)that returns an integer or raises/throws a clear error for empty strings, non-numbers and negative values. - Medium:
Implement a small
Resulttype in TypeScript ({ ok: true, value } | { ok: false, error }) and rewrite a function that throws so it returns a Result instead. Compare the calling code. - Hard:
Write a function that copies one file to another, guaranteeing both files are closed and a half-written output file is deleted if anything fails. Do it in Python with context managers and in Go with defer.
Interview questions
What are the trade-offs between exceptions and error return values?
Exceptions keep the happy path clean and propagate automatically, but make control flow invisible and are easy to forget to handle at the right level. Error values make every failure explicit and checkable by the type system, at the cost of more verbose code (mitigated by things like Rust's ?).
What is the difference between checked and unchecked exceptions in Java?
Checked exceptions (subclasses of Exception but not RuntimeException) must be declared with throws or caught; the compiler enforces it. Unchecked exceptions (RuntimeException and Error) need no declaration and usually indicate programming errors.
What does 'fail fast' mean?
Detect invalid input or state as early as possible and stop immediately with a clear error, instead of continuing and failing later, far from the cause, or silently corrupting data.
What is RAII?
Resource Acquisition Is Initialisation: tying a resource's lifetime to an object's lifetime. The resource is acquired in the constructor and released in the destructor, so it's freed automatically when the object goes out of scope, even during unwinding. Used in C++ and Rust.
How does Go's `defer` work?
defer schedules a function call to run when the surrounding function returns, whether normally or via panic. Deferred calls run in last-in, first-out order, and their arguments are evaluated when defer executes.
What does Rust's `?` operator do?
On a Result, it unwraps Ok(value) to value, or returns early from the function with the Err, converting the error type via From if needed. It works similarly on Option.
When does a `finally` block run?
After the try block (and any matching catch), whether it completed normally, returned, or threw. It's used for cleanup. It won't run if the process is killed or exits abruptly.
Why is an empty catch block dangerous?
It silently discards the error, so the program continues in a possibly invalid state and the failure leaves no trace. Debugging becomes much harder because the symptom appears far from the cause.
What is exception chaining and why is it useful?
Raising a new, higher-level error while keeping the original as its cause (raise X from e in Python, new Error(msg, { cause }) in JS, the cause constructor argument in Java). It gives a meaningful message without losing the root cause's stack trace.
Should you use exceptions for control flow?
Generally no. Exceptions are for exceptional conditions; using them for expected outcomes hides intent and is slower in most runtimes. Python is a partial exception, where EAFP style (try first, catch the error) is idiomatic for things like dictionary lookups.