Python try except: Catch Errors Without Crashing
Python try and except: Catch an Error
A try and except statement lets your program catch an exception instead of crashing. You put the risky code under try:, and the code that handles the problem under except:.
try:
age = int(input())
print("Next year you will be", age + 1)
except ValueError:
print("That is not a whole number.")
print("Goodbye!")That is not a whole number. Goodbye!
The user typed twenty, so int() failed. But instead of a red error, the program printed a friendly message and carried on to Goodbye!. Now type 20 in the Input box and run it again: the except block is skipped.
Think of it like a safety net under a trapeze artist. If the jump goes well, the net does nothing. If they fall, the net catches them, and the show goes on.
How Python runs it
- Python runs the lines in the
tryblock, one by one. - If no error happens, it skips the
exceptblock completely. - If a line fails, Python jumps straight to
except. The rest of thetryblock is skipped. - After either path, the program carries on below.
That's why Next year you will be never printed for twenty: the line above it failed, so Python jumped away.
The rules
tryandexcepteach end with a colon, and their blocks are indented, likeifandelse.exceptlines up with itstry.- A
tryneeds at least oneexcept(or afinally, which you'll meet in the next topic). - Put only the risky lines in the
tryblock. Here, that's theint()line and the line that needs its result.
Common beginner doubt: "Is this the same as checking with if?" They do a similar job. if checks before, which is great when the check is easy, like people > 0. try simply tries, and handles the failure afterwards. Checking whether some text is a valid number is hard with if, but easy with try.
try runs the risky code; if it fails, Python jumps to except, and the program carries on.