In [1]:
name = '2016-03-11-exceptions'
title = 'Dealing with exceptions and errors in Python'
tags = 'basics'
author = 'Denis Sergeev'

In [2]:
from nb_tools import connect_notebook_to_post
from IPython.core.display import HTML

html = connect_notebook_to_post(name, title, tags, author)

Today was an exceptional meeting. Why? Because we talked about such thing as exceptions in Python.

Introduction

Exceptions are errors detected during execution of Python program. By default, these errors result in program interruption, but Python offers you to handle them. This essentially means that you can make your program sturdier and more flexible: it will be able to catch an error and then act accordingly, even without stopping the execution process.

How can you catch an exception? Use the try/except expression. For example:


In [3]:
try:
    # try executing this piece of code
    x = '2' + 3 # this will throw an error, because you can't add integer and string 
except:
    # if there is any error above, go here
    print('an error occured')


an error occured

As you can see, there was an exception due to the incorrect operation of addition. The program, however, wasn't interrupted, but instead caught the exception and printed out a custom message.

The construction above actually handles any exception. But you can specify what error type to handle after the except clause.


In [4]:
try:
    # try executing this piece of code
    x = '2' + 3 # this will throw an error, because you can't add integer and string 
except TypeError:
    # Only if there is TypeError above, go here
    print('TypeError was caught')
except:
    # all other exceptions
    print('I did not expect that')


TypeError was caught

Now the code will print the first message only if a TypeError exception occurred, while any other exceptions will give you the second print message.

You can add as many except cases as you wish. Or you can also combine them, e.g. by writing except (RuntimeError, TypeError, NameError):.

Another useful feature allows you to store the exception information as a context variable. This might be useful if you want to modify or suppress the error message. Or you can use it so that the program can proceed according to an error code (e.g. HTTP errors). For example:


In [5]:
try:
    with open('myfile.txt') as f:
        text = f.read()
except OSError as e:
    print('Some OS error occured. The message is {0}'.format(e))


Some OS error occured. The message is [Errno 2] No such file or directory: 'myfile.txt'

Note that except Exception as e: syntax is correct in Python 3. If you still use Python 2, you should use a comma: except Exception, e:. And stop using Python 2.

Raising Exceptions

You can also invoke errors yourself. The raise statement is used for that.

>>> raise ValueError('some meaningful message...')

Creating your own Exceptions

There is a lot of built-in exceptions in Python: https://docs.python.org/3.5/library/exceptions.html#bltin-exceptions

If you are familiar with Classes in Python, you might find easy and useful to customise your code with user-defined exceptions. They are usually derived from the basic Exception class:


In [6]:
class OhMyUnexpectedError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

In [7]:
try:
    raise OhMyUnexpectedError(123)
except OhMyUnexpectedError as e:
    print('My custom exception occurred with value: ', e)


My custom exception occurred with value:  123

Let's add some fun:


In [8]:
from IPython.display import HTML, display
class OhMyUnexpectedError(Exception):
    def __init__(self, value):
        self.value = value
    def fun(self):
        display(HTML("<img src='https://33.media.tumblr.com/6c933edb44b7ffb4e54bd7cf00ef04d8/tumblr_mvg6t2ov7l1siloiwo1_250.gif', width=300, height=200>"))

And try it out:


In [9]:
try:
    raise OhMyUnexpectedError(123)
except OhMyUnexpectedError as e:
    print('My custom exception occurred with value: ', e)
    e.fun()


My custom exception occurred with value:  123

Ultimate exception handler

Check out this silly exception handler.

Follow-up

This post is just a very brief introduction to exceptions. What you really have to read is Python docs on this topic.


In [10]:
HTML(html)


Out[10]:

This post was written as an IPython (Jupyter) notebook. You can view or download it using nbviewer.