print("TOP")
try:
= []
empty_list = empty_list[0] # triggers IndexError (list index out of range)
matching_item print("EVERYTHING IS GOING FINE") # NEVER REACHED
except IndexError:
print("OOPS - AN ERROR")
print("BOTTOM")
16 Error Handling
Sometimes our programs will encounter errors.
16.1 Handling Errors
In Python, we can use a try... except
block to handle these errors.
After running into an error for the first time, we should observe what type of error we are experiencing (e.g. KeyError
, IndexError
, ZeroDivisionError
, etc.).
Once we know what type of error we need to handle, we should wrap the problematic code inside the try
clause, and specify the known error type in the except
clause:
print("TOP")
try:
100 / 0 # triggers a ZeroDivisionError
print("EVERYTHING IS GOING FINE") # NEVER REACHED
except ZeroDivisionError:
print("OOPS - AN ERROR")
print("BOTTOM")
If we’re not yet sure what type of error we’re experiencing, we can temporarily catch all error classes that inherit from the base error class (Exception
), and once caught, we print the specific error’s datatype to learn how to handle it:
try:
# some hypothetical problematic code
do_something() except Exception as err:
print(type(err)) #> this will tell you the error type
print(err) #> the error message
16.2 Raising Errors
If we find the need to trigger our own errors to stop program execution (less common), we can use the raise
keyword followed by the type of error (e.g. ValueError
):
= ["rock", "paper", "scissors"]
options
= "hoya" # input("Please choose either 'rock', 'paper', or 'scissors': ")
choice
if choice not in options:
raise ValueError("OOPS - Please type 'rock', or 'paper', or 'scissors'.")
16.2.1 Defining and Raising Custom Errors
We can define our own errors if that’s helpful, by inheriting a class from the base Exception
class (or preferably a more specific one):
class MyCustomError(Exception):
pass
raise MyCustomError("My custom message")