Exceptions
Some mistakes only show up while a program runs: dividing by zero, a missing file, text where a number should be. Python then raises an exception, an object that names what went wrong. Follow one through a seven-line program, share.py: it is raised inside a function, climbs out of the function's frame, and is caught by try and except so the program carries on. Then delete the try and watch Python print a traceback and stop.
5 quick questions
Pick an answer to see why. Your score saves with your progress.
01What does Python do when 12 / 0 runs and nothing catches the error?
Dividing by zero has no answer, so Python raises a ZeroDivisionError. With no try around it, Python prints a traceback ending in ZeroDivisionError: division by zero and the program stops.
02In share.py, line 2 raises inside share(). Why does the except on line 5 still catch it?
An exception that is not caught in a function leaves it (its frame is dropped) and continues from the line that called it. Line 4 is inside try, so Python checks the except clauses that belong to that try.
03After the exception is caught in share.py, what value does each hold?
share(12, 0) never returned, so each = ... never ran. Reading each afterwards would raise NameError: name 'each' is not defined.
04Line 5 is changed to except ValueError as err: What happens when share.py runs?
An except clause only catches exceptions of its type (or a subclass). ZeroDivisionError is not a ValueError, so it keeps going, nothing else catches it, and the program stops with a traceback.
05What does print("Oops:", err) show when err is the caught ZeroDivisionError?
print() turns each item into text with str(), and str() of an exception is its message: division by zero.
Glossary
- Exception
- An object Python raises when something goes wrong while a line runs. Its type (such as ZeroDivisionError) says what kind of problem it is, and it carries a message.
- Raise
- To signal an exception. Python raises them itself (12 / 0), and your code can too, with the raise statement.
- try / except
- A guarded block and its handlers. If a line inside try raises, Python jumps to the first except clause whose type matches, instead of stopping.
- as
- In except ZeroDivisionError as err , gives the caught exception object a name so the handler can use it.
- Frame
- The workspace Python makes for one function call, holding its variables. Calls stack frames on top of each other; an escaping exception drops them.
- Call stack
- The pile of frames for the calls that are running right now, newest on top.
- Traceback
- What Python prints for an uncaught exception: the calls that led to it, oldest first, then the exception's type and message.
- Exit status
- A number a program hands back when it ends: 0 means success; an uncaught exception gives 1.
Notes and sources
- On macOS and Linux the command is often python3 rather than python; on Windows the py launcher also works. The $ is the terminal's own prompt: you do not type it.
- The figure shortens the traceback. The real one lists each call, oldest first and newest last, with its file, line number and source line, then the exception type and message. In the real message, the ... is the full path to the file.
- With try and except deleted, the call moves up to line 3 of the file, which is why the real traceback says line 3.
- The / operator always gives a float, so share(12, 3) is 4.0, not 4.
- A bare except: with no exception type catches everything, including mistakes you did not expect; name the exceptions you can actually handle.
- When the except block ends, Python deletes the name err, so copy the exception to another name if you need it later.
- An uncaught exception makes Python exit with status 1; a program that reaches its end normally exits with status 0.
- Python tutorial: Errors and exceptions
- Python reference: The try statement
- Python reference: Execution model, exceptions
- Python library: Built-in exceptions (ZeroDivisionError and the hierarchy)
- Python reference: Function definitions
- Python library: sys.excepthook (printing a traceback)
- Python library: traceback module
- Python glossary: EAFP
Quiz Unlocks after the last step.