Python language basics 60: interrogating the exception

Introduction

In the previous post we saw a couple of ways to handle multiple exception types in the same except block. You can provide a list of exception types separated by a comma or you can have a generic handler where you catch the Exception type.

Exception handling is not as straightforward and easy as it first may seem. Therefore we’ll continue our discussion of the topic by ways of querying the exception object.

Storing the exception in a variable

Occasionally you’ll need to find out more about the exception object in the handler. This is especially true if you are catching an Exception object. You’ll want to find out its type and any arguments stored within it.

We can store the error in a variable using an as-clause. Consider the following version of our previous demo code:

try:
    capitals = {"Stockholm", "Budapest", "Helsinki", "Copenhagen", "Oslo", "Paris"}
    y = 10 / 0
    print("About to remove Washington...")
    capitals.remove("Washington")
except KeyError as err:
    print("No such capital in the collection.")
except Exception as err:
    print(type(err))
    print(err.args)
    print(err)

We have a specific handler for the KeyError which is thrown by the remove method. However, we pretend that the division-by-zero is unexpected. We therefore add a multi-catch clause and store the error in the variable “err”. We then print its type and any arguments stored within it. Finally we print the error which will show it in a user-friendly format. Here’s the output:

(‘division by zero’,)
division by zero

While we are at this example it’s worth noting that if you have multiple handlers then you should list them starting with the most specific type. The following example shows how NOT to do that:

try:
    capitals = {"Stockholm", "Budapest", "Helsinki", "Copenhagen", "Oslo", "Paris"}
    print("About to remove Washington...")
    capitals.remove("Washington")
except Exception as err:
    print(type(err))
    print(err.args)
    print(err)
except KeyError as err:
    print("No such capital in the collection.")

If you run the code you’ll get the following output:

About to remove Washington…

(‘Washington’,)
‘Washington’

I.e. the KeyError handling block was never reached. The reason is that KeyError is also an Exception and the first block that can handle it was the Exception handler. Code execution jumped to the first section that could handle the error and omitted anything else after that.

In the next post we’ll see how to actively throw exceptions in code.

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.

2 Responses to Python language basics 60: interrogating the exception

  1. Pingback: Python language basics 60: interrogating the exception | Dinesh Ram Kali.

  2. 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: