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.
| Stage | Responsibility | Typical construct |
|---|---|---|
| Detection | Recognize that a precondition or operation failed | Validation check, failed system call |
| Signaling | Represent the failure as data or control flow | Raised exception, error value, status code |
| Propagation | Pass the failure to a caller with more context | Unwinding stack, returned error, ? operator |
| Recovery or reporting | Retry, fall back, abort or inform the user | Catch block, match expression, top-level handler |
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.
| Mechanism | How it signals failure | Typical languages | Main weakness |
|---|---|---|---|
| Return codes | Special value or status integer | C, POSIX system calls | Easy to ignore silently |
| Exceptions | Non-local jump to a matching handler | Java, Python, C#, C++ | Hidden control flow |
| Result types | Value that holds success or error | Rust, Haskell, Swift | More verbose call sites |
| Multiple return values | Explicit error value beside the result | Go | Repetitive checking code |
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 category | Example | Recommended reaction |
|---|---|---|
| Invalid input | Malformed date entered by a user | Reject with a clear, specific message |
| Transient failure | Network timeout, locked database row | Retry with backoff and a retry limit |
| Resource failure | Disk full, file permission denied | Report, release resources, degrade gracefully |
| Programming bug | Null dereference, violated invariant | Fail fast, log the stack trace, fix the code |
| Fatal environment error | Out of memory, corrupted installation | Terminate cleanly with diagnostic output |
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,withstatements 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.
| Symptom | Cause | Fix |
|---|---|---|
| Data quietly wrong | Empty catch block swallows the error | Log and rethrow or handle explicitly |
| Useless log entries | Original cause discarded when wrapping | Chain the underlying error |
| Unexpected crashes in production | Unchecked return value or null result | Use result types or linters |
| Leaked connections | Cleanup skipped on the error path | Use scoped resource management |
| Security leaks in messages | Stack traces shown to end users | Return generic messages, log details |
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.