Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 149 ยท Files and Errors

Raising Exceptions

Learn to raise exceptions in Python with raise, choose the right exception type, re-raise errors you can't handle, and chain exceptions with raise ... from.

In the previous lesson you caught exceptions that Python raised for you. Now it's your turn. When a function receives input it can't work with, the right response is usually not to print a message or return a strange value, but to raise an exception that tells the caller exactly what went wrong.

In this lesson you'll use the raise statement, pick a fitting exception type, re-raise an exception after doing some work, and connect one exception to another with exception chaining. Together these let your functions fail loudly, clearly and early.

The raise statement

To raise an exception, create an exception object and pass it to raise. The message is the argument:

Python Raising an exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first two calls work. The third one raises ValueError, and because nothing catches it, the program stops with a traceback that ends in your own message. As soon as raise runs, the function stops: no further lines in it execute, and nothing is returned.

A good error message says what was expected and what actually arrived. "volume must be between 0 and 100, got 140" lets whoever reads the traceback fix the problem without opening your code.

Tip: you can write raise ValueError without parentheses, and Python creates the object for you. It works, but an exception without a message is much harder to debug, so include one.

Why raise instead of returning a flag?

Beginners often signal failure with a special return value such as -1, None or False. The trouble is that the caller can easily forget to check it, and the bad value travels on until it causes a confusing error somewhere else:

Python
def find_price(prices, item):
    if item not in prices:
        return -1          # easy to miss
    return prices[item]

total = find_price(prices, "juice") * 3   # silently -3

An exception can't be ignored by accident. Either someone handles it on purpose, or the program stops right at the source of the problem. That's what "fail early" means.

Choosing the right exception type

Raise a built-in exception whose meaning matches the situation. The most useful ones for your own functions are:

  • ValueError: the argument has the right type but an unacceptable value (negative quantity, empty name, unknown option).
  • TypeError: the argument is the wrong kind of thing entirely (a string where a number is needed).
  • KeyError / IndexError: something wasn't found in a mapping or sequence.
  • RuntimeError: something went wrong that doesn't fit any other category.
  • NotImplementedError: a method that a subclass is supposed to provide hasn't been written yet.

Callers often catch exceptions by type, so a fitting type matters. If your function raises ValueError for bad input, the caller's except ValueError: works exactly as it would for int("abc").

Python Validating arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The function raises, the caller handles. That separation is the heart of exception-based design: the low-level code knows what went wrong, while the high-level code decides what to do about it (show a message, skip a record, ask again).

When none of the built-in types describe your error well, create your own. That's the topic of Custom Exceptions.

Re-raising an exception

Sometimes you want to notice an exception, do something about it (such as logging it or cleaning up), and then let it continue upward because you can't truly fix it. A bare raise inside an except block does exactly that: it re-raises the exception currently being handled, with its original traceback intact.

Python Re-raising

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

load_number() records the failure but doesn't pretend to recover from it, so the caller still gets the original ValueError and its message.

Exception chaining with from

Often the most helpful thing is to translate a low-level error into one that makes sense at your level. A configuration loader shouldn't leak a bare KeyError: 'port' to its caller; it should say "the config is missing a port". But you don't want to throw away the original error either, because it points at the exact cause.

raise NewError(...) from original does both. It raises the new exception and stores the original one as its cause:

Python raise ... from

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The loop shows that the new exception keeps a link to the original in its __cause__ attribute. The last line isn't caught, so look at its traceback: Python prints both exceptions, joined by the sentence "The above exception was the direct cause of the following exception". You get the friendly, high-level message and the low-level detail.

Implicit chaining and from None

If an exception happens while you're handling another one without using from, Python still links them, but the traceback says "During handling of the above exception, another exception occurred". That wording suggests a bug in your error handler, so when the translation is intentional, write from error to make it explicit.

Occasionally the original exception is just noise, for example when you've already put all the useful information into the new message. raise NewError(...) from None hides the chain entirely:

Python
try:
    level = LEVELS[name]
except KeyError:
    raise ValueError(f"unknown level {name!r}; choose from {list(LEVELS)}") from None

Adding notes to an exception

Since Python 3.11, every exception has an add_note() method. Notes are extra lines printed below the message in the traceback. They're useful when you want to add context while re-raising the same exception:

Python add_note()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The traceback shows the original ValueError and, underneath, your note saying which line was the problem.

Watch out: don't raise Exception itself (raise Exception("bad")). Callers can then only catch it with except Exception, which also catches every other error. Pick a specific built-in type or define your own.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to the rest of a function after a raise statement runs?

    raise ends the function at once. The exception moves up the call stack until an except clause handles it, or the program stops.
  2. 2. A function receives -5 as a quantity, which must be positive. Which exception fits best?

    The type (a number) is fine but the value is not acceptable, which is exactly what ValueError means.
  3. 3. What does a bare raise do inside an except block?

    A bare raise re-raises the active exception with its original type, message and traceback.
  4. 4. What does raise ConfigError("bad port") from error add compared to a plain raise?

    Using from links the new exception to its cause. Use from None if you want to hide the original instead.

Summary

  • raise SomeError("message") stops the current function and sends the exception to the caller.
  • Prefer raising over returning special values like -1 or None for errors; exceptions can't be ignored by accident.
  • Pick a fitting type: ValueError for bad values, TypeError for wrong types, and so on. Write messages that say what was expected and what arrived.
  • A bare raise inside except re-raises the current exception unchanged.
  • raise New(...) from error translates an error while keeping its cause; from None hides the cause.
  • error.add_note() (Python 3.11+) attaches extra context to an exception.

Next: Custom Exceptions, where you'll define your own exception classes and hierarchies.