Python language basics 61: raising exceptions

Introduction

In the previous post we saw how to extract some useful information from an exception in Python. We discussed how to store the exception in a variable using an “as” clause and how to read its type and arguments.

In this post we’ll see how to use the “raise” keyword to re-raise or re-throw an exception.

The raise keyword

Raising an exception can be helpful in order to let an exception bubble up the call stack instead of silently suppressing it.

Consider the following code:

def divide(first, second):
    res = 0
    try:
        res = first / second
    except ZeroDivisionError:
        res = -1
    return res

res = divide(10, 2)
print(res)

The function will return 5 of course. However, if you call the function with 10 and 0 then it returns -1. We catch the zero division error in the divide function and return an error code of -1. However, it can be misleading. Calling the function with e.g. 10 and -10 will also return -1. The error code alone will be an ambiguous result.

It’s a better strategy to catch the exception, handle it in some way if you wish, e.g. log it and then re-raise it so that the exception isn’t lost along the way. In general you should let exceptions bubble up the call stack so that you can discover them and fix them.

Raising an exception in Python is done with the “raise” keyword:

def divide(first, second):
    res = 0
    try:
        res = first / second
    except ZeroDivisionError:
        print("Big NONO")
        raise
    return res

res = divide(10, 0)
print(res)

You’ll see the following output in PyCharm if you run the above code – the exact code lines and file names will most certainly differ:

Big NONO
Traceback (most recent call last):
File “C:/PythonProjects/HelloWorld/Various.py”, line 10, in
res = divide(10, 0)
File “C:/PythonProjects/HelloWorld/Various.py”, line 4, in divide
res = first / second
ZeroDivisionError: division by zero

Make sure you call “raise” as you see in the example so that all the information about the exception is preserved when it’s re-raised, or rethrown.

We can then catch the exception when calling the divide function:

def divide(first, second):
    res = 0
    try:
        res = first / second
    except ZeroDivisionError:
        print("Big NONO")
        raise
    return res

try:
    res = divide(10, 0)
    print(res)
except Exception as err:
    print(type(err))
    print(err.args)
    print(err)

The above code will result in the following output:

Big NONO

(‘division by zero’,)
division by zero

In the next post we’ll see how to run code even after an exception is thrown using the finally block.

Read all Python-related posts on this blog here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Python language basics 61: raising exceptions

  1. Pingback: Python language basics 61: raising exceptions | Dinesh Ram Kali.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: