Error handling

On this page 7

Error handling is the set of techniques a program uses to detect, signal, propagate and recover from failures during execution, so that a fault in one operation does not silently corrupt data or crash the whole system. It is one of the core programming fundamentals, because every non-trivial program depends on files, networks, user input and other resources that can fail at any moment.

Good error handling makes failures explicit, contained and diagnosable. It decides where an error is noticed, who is responsible for reacting to it, what the user sees and what information reaches the logs. Languages offer different mechanisms for this, from return codes and exceptions to result types, but the underlying design questions remain the same.

How error handling works in a program

Every error handling strategy follows the same four-stage path: an operation detects that it cannot fulfill its contract, it signals that condition, the signal travels up the call stack, and some caller with enough context decides how to respond. The key design decision is where each stage happens, because the code that detects a problem rarely knows how to fix it.

A function that reads a configuration file, for example, can detect that the file is missing, but only the application startup code knows whether to use defaults, prompt the user or stop. This separation is the principle of handling errors at the right level: low-level code reports precisely, high-level code decides.

The following table shows how the four stages map to concrete responsibilities in typical code.

StageResponsibilityTypical construct
DetectionRecognize that a precondition or operation failedValidation check, failed system call
SignalingRepresent the failure as data or control flowRaised exception, error value, status code
PropagationPass the failure to a caller with more contextUnwinding stack, returned error, ? operator
Recovery or reportingRetry, fall back, abort or inform the userCatch block, match expression, top-level handler
Stages of error handling

Error handling mechanisms across languages

Programming languages implement error handling through three main mechanisms, and each shapes how visible failures are in the source code. The choice affects readability, performance and how easily a developer can forget to handle a failure.

MechanismHow it signals failureTypical languagesMain weakness
Return codesSpecial value or status integerC, POSIX system callsEasy to ignore silently
ExceptionsNon-local jump to a matching handlerJava, Python, C#, C++Hidden control flow
Result typesValue that holds success or errorRust, Haskell, SwiftMore verbose call sites
Multiple return valuesExplicit error value beside the resultGoRepetitive checking code
Main error signaling mechanisms

Exceptions separate the happy path from failure code, which keeps business logic readable, but they make it hard to see which lines can fail. Result types make failure part of the function signature, so the compiler with static typing can force callers to deal with it. Java’s checked exceptions attempted a similar guarantee and remain controversial because they encourage empty catch blocks.

Kinds of errors and appropriate responses

Not every error deserves the same treatment, and a mature design distinguishes recoverable conditions from programming bugs. A missing network connection is an expected operational failure; an index out of range is usually a defect that no amount of retrying will fix.

Error categoryExampleRecommended reaction
Invalid inputMalformed date entered by a userReject with a clear, specific message
Transient failureNetwork timeout, locked database rowRetry with backoff and a retry limit
Resource failureDisk full, file permission deniedReport, release resources, degrade gracefully
Programming bugNull dereference, violated invariantFail fast, log the stack trace, fix the code
Fatal environment errorOut of memory, corrupted installationTerminate cleanly with diagnostic output
Error categories and recommended reactions

The fail-fast principle says that a program should stop as soon as it detects an impossible state, because continuing risks writing corrupt data. Assertions and panics serve this purpose. In contrast, graceful degradation keeps a service partly available, for example showing cached prices when the pricing service is down.

Designing robust error handling

Robust error handling depends on a few consistent conventions applied throughout a codebase rather than clever individual handlers. The most valuable practices are simple to state and hard to enforce without code review.

  • Preserve context: wrap lower-level errors with a description of what the program was attempting, keeping the original cause attached.
  • Release resources reliably using finally, defer, with statements or destructors, so failures do not leak files or locks.
  • Catch narrowly: handle only the specific error types the code can actually address.
  • Separate user messages from diagnostics: show users a clear action, send stack traces and identifiers to logs.
  • Validate at boundaries: check external input once, where it enters the system, rather than everywhere.

Performance also matters. In most languages with exceptions, throwing is expensive compared with returning a value, because the runtime must unwind the stack and often capture a trace. Exceptions should therefore signal exceptional situations, not ordinary control flow such as ending a loop.

Common error handling mistakes

Most error handling defects come from silencing or misreporting failures rather than from missing handlers. The table below lists frequent symptoms, their causes and the usual corrections.

SymptomCauseFix
Data quietly wrongEmpty catch block swallows the errorLog and rethrow or handle explicitly
Useless log entriesOriginal cause discarded when wrappingChain the underlying error
Unexpected crashes in productionUnchecked return value or null resultUse result types or linters
Leaked connectionsCleanup skipped on the error pathUse scoped resource management
Security leaks in messagesStack traces shown to end usersReturn generic messages, log details
Frequent mistakes and their fixes

A related mistake is catching too broadly, such as catching every exception at a low level and returning a default value. This hides genuine bugs and makes failures appear far from their cause, which multiplies debugging time.

A plain-language summary

Programs constantly run into problems: a file is missing, the internet drops, or someone types letters where a number belongs. Error handling is how a program notices these problems and responds sensibly instead of crashing or giving wrong answers.

It works like a well-run restaurant. If the kitchen runs out of an ingredient, the cook tells the waiter, and the waiter offers the guest an alternative. The problem is reported to the person who can actually decide what to do.

An example from practice

An online store processes payments through an external payment service. During a busy holiday weekend, the service occasionally answers with timeouts. The checkout code treats a timeout as a transient failure and retries up to three times with increasing delays of 200, 400 and 800 milliseconds.

If all retries fail, the code does not show the customer a technical stack trace. It records the order as pending, logs the error with a unique identifier, and tells the customer that payment confirmation will arrive by email. A background job later checks the payment status using an idempotency key, so the customer is never charged twice.

When a developer finds a separate bug in the discount calculation, that error is not retried: the code fails fast, alerts the team and keeps the faulty order from shipping. As a result, the store loses almost no orders during the outage and fixes the bug the same day.