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.
A function that refuses negative input:
When the bad input arrives, the function raises and never returns:
What will be the output?
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:
What will be the output?
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:
What will be the output?
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:
What will be the output?
What will be the output?
What will be the output?