Exceptions and Error Handling

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[10]
Traceback (most recent call last):
File "
", line 1, in
x[10]
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[10]
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[10]
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:

  • RuntimeError
  • ValueError
  • TypeError
  • NotImplementedError

Leave A Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

<code> For inline code.
[sourcecode] For multiline code.