Whenever an error is encountered in your program, Python will raise an exception stating the line number and what went wrong:
x = [1,2,3] x Traceback (most recent call last): File " ", line 1, in x IndexError: list index out of range
If we want the code to continue running, we can use a try/except block:
x = [1,2,3] try: x except IndexError: print("What are you trying to pull?") print("Continuing program...")
Another variation includes both the else and finally statements, both of which are optional.
x = [1,2,3] try: x except IndexError: print('What are you trying to pull?') else: # Will only run if no exception was raised print('No exception was encountered') finally: print('This will run whether there is an exception or not') print("Continuing program...")
You can raise your own exception if you want to prevent the script from running:
if func() == 'bad return value': raise RuntimeError('Something bad happened')
There are many different types of built-in exceptions that you can raise. You can even create your own types of exceptions. To read more about the different types of built-in exceptions visit the documentation here.
Exceptions that I regularly use include: