Every programmer sees errors, every day. An error is not a failure: it is Python telling you exactly what went wrong and on which line. This guide shows how to read errors, and how to handle them with try and except.
READING AN ERROR MESSAGE
When Python stops with an error, read the last line first. It tells you the type of error and a short reason.
age = int("twelve")
ValueError: invalid literal for int() with base 10: 'twelve'
Translation: int() could not turn the text "twelve" into a number.
ERRORS YOU WILL MEET FIRST
SyntaxError: the code is not valid Python (missing colon, bracket or quote).NameError: you used a name that does not exist (often a typo).TypeError: wrong type, like"Score: " + 5.ValueError: right type, wrong value, likeint("abc").IndexError/KeyError: that position or key is not there.ZeroDivisionError: dividing by zero.
TRY / EXCEPT: CATCH THE ERROR
Put risky code in try. If an error happens, Python jumps to except instead of crashing.
text = "twelve"
try:
age = int(text)
print("Next year you will be", age + 1)
except ValueError:
print("Please type a number, like 12")Please type a number, like 12
except ValueError:). A bare except: also hides typos and real bugs.ELSE AND FINALLY
for value in ["8", "x"]:
try:
n = int(value)
except ValueError:
print(value, "is not a number")
else:
print(value, "doubled is", n * 2)
finally:
print("checked", value)8 doubled is 16
checked 8
x is not a number
checked x
else runs only when there was no error. finally always runs.
try:
print(10 / 0)
except ZeroDivisionError:
print("oops")
print("done")ZeroDivisionError, so except prints "oops". The program then carries on and prints "done".DEBUGGING TIPS
- Read the last line of the error, then look at the line number above it.
- Add a
print()before the failing line to see what your variables really contain. - Change one thing at a time, then run again.
COMMON BEGINNER MISTAKES
except: pass. The program "works" but silently does the wrong thing.try. Keep only the risky line or two there.data = {"hp": 5}
try:
print(data["mana"])
except KeyError:
print("no mana")
except ValueError:
print("bad value")KeyError. Only the first matching except runs.PRACTICE IT, DON'T JUST READ IT
Bug Bay in Snekcade is all about debugging: squash 10 bugs in a broken game, with hints that get more specific each time you ask.
PLAY BUG BAY ▸FAQ
How do I read a Python error message?
Start at the last line: it names the error type and gives a short reason. The lines above show which line of your code caused it.
What is the difference between SyntaxError and other errors?
A SyntaxError means the code is not valid Python, so it does not run at all. Other errors happen while the code is running.
Should I use a bare except?
Usually not. Catch the specific error you expect, like except ValueError, so real bugs are not hidden.