Handling Errors (try / except)
How to keep your program calm when something goes wrong
"cat" into a number. Normally the program crashes and stops. With try / except you can catch that problem and let your program keep going, showing a friendly message instead of an ugly error.
- explain what an exception (a runtime error) is,
- write a
try / exceptblock to catch an error, - catch the right error, like
ValueErrororZeroDivisionError, - make a program that fails gracefully instead of crashing.
1. What is an exception?
An exception is an error that happens while your program is running. Python notices that it cannot do what you asked, so it stops and prints an error message called a traceback.
Here is a tiny program with no protection. If the person types something that is not a whole number, it breaks:
number = int(input("Enter a number: "))
print("Double is", number * 2)
If the person types cat instead of a number, Python crashes with this traceback:
Traceback (most recent call last):
File "program.py", line 1, in <module>
number = int(input("Enter a number: "))
ValueError: invalid literal for int() with base 10: 'cat'
The last line, ValueError, is the name of the exception. Every kind of error has a name. Once you know the name, you can catch it.
2. The analogy: a safety net
Think of a tightrope walker high in the air. Most of the time they walk across just fine. But if they slip, a safety net catches them so they are not hurt — the show goes on.
try is you walking the rope. except is the safety net below. If nothing goes wrong, the net is never used. But if you slip (an error happens), the net catches you and your program keeps running instead of crashing to the ground.