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.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: