This Python Try...Except lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
try watches a block for errors. except runs when a matching error happens. else runs when nothing was raised. finally runs either way.
Catch a specific error, such as ValueError or ZeroDivisionError. A bare except hides bugs.
Example 1: Start here
Print a useful message or re-raise. Do not swallow the error with pass.
try: # watch the next lines for an error
print(10 / 0) # the math runs, then print shows the result
except ZeroDivisionError: # runs when the try block fails
print("Cannot divide by zero")
Example 2: Catch a bad number
int raises ValueError when the text is not a number. except handles that case.
try: # watch the next lines for an error
n = int("twelve") # text read as a whole number
except ValueError: # runs when the try block fails
n = 0 # a whole number
print(n)
Example 3: else and finally
else runs when nothing was raised. finally runs either way.
try: # watch the next lines for an error
n = int("12") # text read as a whole number
except ValueError: # runs when the try block fails
print("bad")
else: # runs when the test above was false
print(n)
finally: # runs whether or not an error happened
print("done")
Example 4: Raise your own error
raise stops the function. The except below prints the message.
def fee(amount): # define the function; it runs when you call it
if amount < 0: # run the indented lines only when this is true
raise ValueError("fee cannot be negative") # stop and report an error
return amount # send this value back to the caller
try: # watch the next lines for an error
fee(-1) # call the function
except ValueError as error: # runs when the try block fails
print(error)
