Skip to content
Velloreth
Programming 7 min read

Exceptions vs Error Codes: Choosing the Right One

Exceptions and error codes are two ways to signal failure. Learn the trade-offs, when each fits, and why most languages use both.

By

Two mechanisms, one job

Both exceptions and error codes signal that something went wrong. They differ in how the signal travels and who is responsible for noticing it.

Exceptions interrupt normal flow and propagate up the call stack until a handler catches them. If nothing catches, the program terminates.

Error codes are return values. Normal flow continues, and the caller must check the value to discover the failure.

// Exception
function divide(a, b) {
  if (b === 0) throw new Error('Division by zero');
  return a / b;
}

// Error code
function divide(a, b) {
  if (b === 0) return { error: 'Division by zero' };
  return { value: a / b };
}

The difference looks small. The consequences are large.

The core trade-off

ExceptionsError codes
Can be ignoredNoYes
Visible in signatureNoYes
Happy path clarityHighLower
VerbosityLowHigh
Stack traceYesNo
Cost when not thrownNear zeroA check per call
Cost when thrownHighLow
Composes with callbacksPoorlyWell

The two columns are almost exact opposites, which is why the choice is genuinely a trade-off rather than a matter of one being correct.

The case for exceptions

They cannot be ignored. If a function throws and nothing catches, the program fails loudly. That is the right default for a bug.

The happy path stays clean. Compare:

// Error codes: every call needs a check
const a = readFile('a.txt');
if (a.error) return a;
const b = parse(a.value);
if (b.error) return b;
const c = transform(b.value);
if (c.error) return c;
return c.value;
// Exceptions: the happy path is the code
const a = readFile('a.txt');
const b = parse(a);
const c = transform(b);
return c;

The second version says what it does. The first is dominated by error plumbing.

They carry a stack trace. When an exception is thrown, the runtime records where it came from. That is invaluable for debugging, and error codes have no equivalent.

They propagate through layers automatically. A function deep in a call stack can fail, and the error reaches a handler at the top without every intermediate function knowing about it.

The case for error codes

They are visible. The signature tells you the function can fail:

func ReadConfig(path string) (*Config, error)

In Go, the error return is part of the type. A caller who ignores it is making a visible choice, and linters flag it.

They are cheap. Throwing an exception captures a stack trace and unwinds the stack, which is expensive. Returning a value is not.

They compose with callbacks and streams. An exception thrown inside an asynchronous callback cannot be caught by the caller’s try/catch, because the callback runs in a different stack. Error codes work fine.

They make control flow explicit. You can see exactly where a failure is handled, because it is a branch in the code.

The Go model

Go is the most prominent error-code language, and its model is worth understanding.

func LoadUser(id string) (*User, error) {
    row := db.QueryRow("SELECT * FROM users WHERE id = $1", id)
    var u User
    if err := row.Scan(&u.ID, &u.Name); err != nil {
        return nil, fmt.Errorf("load user %s: %w", id, err)
    }
    return &u, nil
}

The conventions:

  • error is the last return value.
  • nil means success.
  • fmt.Errorf with %w wraps the error, preserving the chain.
  • Callers check with if err != nil.

The criticism is verbosity — if err != nil appears constantly. The defence is that the failure is impossible to miss, and Go’s designers consider that worth the noise.

The real risk is ignoring the error:

user, _ := LoadUser(id) // the underscore discards the error

This compiles and runs. The failure is silent. Linters catch it, but the language does not.

The Rust model

Rust takes a third approach: a result type in the type system.

fn load_user(id: &str) -> Result<User, DbError> {
    let row = db.query("SELECT * FROM users WHERE id = $1", &[id])?;
    Ok(User::from_row(row))
}

Result<T, E> is either Ok(value) or Err(error). The ? operator propagates an error to the caller, which is concise like an exception but explicit like an error code.

The key property is that the compiler enforces handling. You cannot use the value without dealing with the error, because the value is wrapped. There is no way to accidentally ignore it.

This is arguably the best of both: explicit in the type, concise in the code, and impossible to forget.

The JavaScript and Python model

Both use exceptions, with a convention of returning null or a sentinel for expected failures.

// Exception for unexpected
function parseJSON(text) {
  return JSON.parse(text); // throws on invalid input
}

// Null for expected
function findUser(users, id) {
  return users.find((u) => u.id === id) ?? null;
}

The convention is: throw for things that should not happen, return a sentinel for things that routinely do.

The problem is that the sentinel is easy to forget:

const user = findUser(users, id);
console.log(user.name); // TypeError if user is null

TypeScript mitigates this with strict null checks, which force the caller to handle the null case. That is the type system doing what the language does not.

When to use which

Use exceptions for:

  • Programmer errors — null dereference, invalid state, broken invariants.
  • Unrecoverable conditions — missing configuration, failed startup.
  • Deep failures that only a high-level handler can deal with.
  • Anything where the happy path clarity matters more than explicitness.

Use error codes or result types for:

  • Expected failures — validation, not found, permission denied.
  • Failures the immediate caller must handle.
  • Performance-critical paths where throwing is too expensive.
  • Asynchronous boundaries where exceptions do not propagate.

The dividing line is expectation. If the failure is routine, make it explicit. If it indicates a bug, throw.

The anti-patterns

Using exceptions for control flow.

// Bad: exceptions as a loop condition
try {
  while (true) {
    const item = queue.pop(); // throws when empty
    process(item);
  }
} catch (e) {
  // done
}

This is slow and obscures intent. Check the condition instead.

Catching and ignoring.

try {
  riskyOperation();
} catch (e) {}

The failure disappears. If you catch, do something.

Catching too broadly.

try {
  const user = await getUser(id);
  const posts = await getPosts(user.id);
  await sendEmail(user.email);
} catch (e) {
  return res.status(500).json({ error: 'Something failed' });
}

Three different operations, one generic handler. The caller cannot tell whether the user was missing, the posts failed, or the email bounced. Catch narrowly, or distinguish by error type.

Returning error codes and exceptions from the same function. Pick one contract per function and document it.

Ignoring a returned error. The Go _ and the JavaScript unhandled promise rejection are the same bug in different clothes.

Practical guidance

  • Decide per function which mechanism it uses, and be consistent.
  • Throw for bugs, return for expectations.
  • Never ignore a returned error — check it or propagate it.
  • Catch narrowly and handle specifically.
  • Use result types where the language supports them and the failure is expected.
  • Do not use exceptions for control flow.
  • Document the contract — a function that throws should say so.

For the broader patterns, see error handling patterns that actually work and null vs undefined vs nil. For the async boundary problem, promises vs async/await and callbacks explained.

Quotable summary

Exceptions propagate automatically and cannot be ignored, keeping the happy path clean and carrying a stack trace, but they are invisible in the signature and expensive to throw. Error codes are explicit and visible in the type, cheap, and compose with callbacks, but they can be silently ignored and add verbosity. Exceptions suit unexpected failures that should abort an operation; error codes and result types suit expected failures that callers routinely handle. Rust’s Result with the ? operator combines the explicitness of error codes with the conciseness of exceptions, and the compiler enforces handling. Most languages use both mechanisms, and the dividing line is expectation: throw for bugs, return for routine failures.

Frequently asked questions

What is the difference between an exception and an error code?
An exception is thrown and propagates up the call stack until something catches it, interrupting normal flow. An error code is a return value the caller must check, so normal flow continues and the failure is handled explicitly.
Why do some languages prefer error codes?
Because they make failure visible in the function signature, so callers cannot forget it exists. Go and C use this style. The trade-off is verbosity and the risk that a caller ignores the returned error.
Why do some languages prefer exceptions?
Because they cannot be ignored, they keep the happy path uncluttered, and they carry a stack trace. Java, Python, C#, and JavaScript use them. The trade-off is that control flow becomes implicit and exceptions can be expensive.
Are exceptions slow?
Throwing and catching is expensive in most runtimes because it captures a stack trace and unwinds the stack. The cost only matters if exceptions are used for ordinary control flow, which is an anti-pattern.
What is a result type?
A result type is a value that represents either success with a value or failure with an error, such as Rust's Result or a discriminated union in TypeScript. It makes failure explicit in the type system without exceptions.
Should I use exceptions for validation errors?
Usually not. Validation failures are expected and callers must handle them, so a result type or a returned error is clearer. Reserve exceptions for conditions that indicate a bug or an unrecoverable state.