Error Handling

Raising exceptions with raise

You can trigger exceptions yourself with the raise keyword. This is the standard Python way to signal that an input is invalid or a precondition was not met.


So far you've reacted to errors. Now you'll trigger them yourself. The raise keyword tells Python: stop, this situation is invalid.

Basic syntax: pick an exception class and pass a message.

Python

A function that refuses negative input:

Python
Output

When the bad input arrives, the function raises and never returns:

Python
Output

What will be the output?

Python

Pick the exception class that fits the problem. ValueError signals a bad value, TypeError signals the wrong kind of object.

A type check using TypeError:

Python
Output

What will be the output?

Python

Inside an except block, a bare raise re-raises the exception you just caught. This is useful for logging the error and still letting it bubble up.

Re-raise after recording what happened:

Python
Output

What will be the output?

Python

Raised exceptions travel up through every function call until something catches them, or the program exits with a traceback.

The exception propagates from inner() through outer() and is caught at the top:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python