Assertions

Assertions Versus Exceptions: When to Use Each

By AssertArc Editorial Team · · 4 min read

Assertions and exceptions both stop a program when something is wrong, so they are easy to confuse. In code they can even look alike: a condition is checked, and if it fails, the program raises an error. The difference lies in what the check means and who is responsible for the problem.

An exception reports a situation that can reasonably happen while the program runs correctly. An assertion states something that must be true if the code itself is correct. Keeping those two ideas apart makes error handling clearer and bugs easier to find.

What an assertion is

An assertion is a statement about your own assumptions. It says, "At this point in the code, this condition must hold." If it does not, then the program has a bug, not a bad input or an unlucky environment.

In Python, the syntax is the assert keyword.

def average(values):
    total = sum(values)
    count = len(values)
    assert count > 0, "average() was called with no values"
    return total / count

Here the assertion documents that callers inside the codebase must never pass an empty list. If one does, the failure points directly at a programming mistake that must be fixed, not handled.

What an exception is

An exception represents a problem that the program can anticipate and, ideally, respond to. A file might be missing, a network might drop, a user might type text where a number is expected. None of these is a bug in your logic. They are facts of the world.

def read_config(path):
    try:
        with open(path) as handle:
            return handle.read()
    except FileNotFoundError:
        raise SystemExit(f"Config file not found: {path}")

Here the code expects that the file may be absent, and it responds with a clear message. The calling code can also catch exceptions, retry, use a default, or log and continue.

A simple rule of thumb

Ask who is at fault if the check fails.

  • If a caller, a user, a file or an outside system caused it, use an exception.
  • If your own code broke its own rules, use an assertion.

Another way to see it: an exception is part of the contract with the outside world, and an assertion is a note to future maintainers about what the code relies on.

Never rely on assertions for validation

Many languages allow assertions to be turned off. Python skips assert statements when you run it with the -O flag, and Java disables them by default unless you enable them with a flag. That means an assertion can vanish in production.

This is the critical consequence: never use an assertion to validate input or enforce security. The following is a mistake.

def withdraw(amount):
    assert amount > 0   # wrong: removed when assertions are disabled

If input can come from outside, use a real check that always runs.

def withdraw(amount):
    if amount <= 0:
        raise ValueError("amount must be positive")

Because the ValueError is an ordinary exception, it runs in every mode and can be handled by the caller.

Good places for assertions

Assertions earn their place in these situations:

  1. Internal invariants. A sorted list must stay sorted after an insert, or a counter must never go negative.
  2. Impossible branches. In an if/elif chain that should cover every case, add an assertion in the final else to catch an unhandled value.
  3. Pre and post conditions between private functions. Checking the result of a complicated calculation before returning it.
  4. Test code. Test frameworks are built around assertions, since a failing check should immediately flag a broken expectation.

An assertion also works as executable documentation. A line such as assert node.parent is not None tells the next reader something that a comment might get wrong over time.

Good places for exceptions

Use exceptions for:

  • Invalid input from users, files or networks.
  • Missing resources, such as files, database rows or permissions.
  • Operations that can fail for reasons outside your control.
  • Public API boundaries, where you must tell callers what they did wrong.

Pick specific exception types, such as ValueError or a custom error class, and write messages that say what happened and what a person can do about it. Avoid catching a broad Exception unless you re-raise or log it, since that hides real bugs.

Writing helpful assertion messages

An assertion with a message is much easier to debug. Include the values involved, not only a description.

assert 0 <= index < len(items), f"index {index} out of range for {len(items)} items"

When it fails, the message tells you immediately what went wrong, without a debugger session.

Avoid side effects inside assertions

Because assertions may be removed, the expression inside them should never change state. Writing assert queue.pop() is not None removes an item only when assertions are on, which creates a bug that appears in one mode and not the other. Do the work on its own line, then assert on the stored result.

Frequently Asked Questions

Should I leave assertions on in production?

It depends on the language and the risk. Some teams keep them on because a loud failure beats silent corruption, and others disable them for performance. Whichever you choose, do not let correctness of user facing behaviour depend on them.

Can I catch an AssertionError?

You can, but you usually should not. An assertion failure signals a bug, so the right response is to log it and fix the code. Catching it to continue as if nothing happened hides the very problem the assertion was written to expose.

Are assertions the same as unit test assertions?

They share the same idea, a statement that must be true, but they live in different places. Test assertions check the code from outside as part of a test run, while assertions in source code check assumptions at runtime inside the program.

Related reading