Python language basics 58: exception handling in code

Introduction

In the previous post we started discussing exceptions and errors. We looked at a couple of important terms, such as throwing, catching and handling exceptions. Good exception handling will make your application more stable. Your users may still be irritated by exception messages but it’s nothing compared to how they feel when an application simply crashes, closes by itself or even freezes the device it’s running on so that it needs rebooting.

In this post we’ll look at how to handle exceptions in code.

try-except

The new keywords in python we need to look at is “try” and “except”. “Except” corresponds to catching the exception. The except-block contains the exception handling logic. The try-block precedes the except-block and it simply contains the code we want to execute – or we try to execute.

If you execute the following code…

capitals = {"Stockholm", "Budapest", "Helsinki", "Copenhagen", "Oslo", "Paris"}
capitals.remove("Washington")

…then an exception will be thrown as the capitals collection does not include Washington. The behaviour of the remove method is such that it throws an exception if the referenced object is not found in the collection. The full exception message in PyCharm looks as follows:

Traceback (most recent call last):
File “C:/PythonProjects/HelloWorld/Various.py”, line 2, in
capitals.remove(“Washington”)
KeyError: ‘Washington’

Process finished with exit code 1

The traceback section shows the stacktrace at the moment the exception was thrown. It says that the exception was thrown on line 2 of the code. A stack trace is a very important tool when you’re trying to find the source of an exception, i.e. where in the code the exception was thrown. It’s usually not enough to see that an exception was thrown, you’ll need to find the source and fix it to make the application better.

Here’s how you can catch the KeyError exception and print some useful message to the user:

try:
    capitals = {"Stockholm", "Budapest", "Helsinki", "Copenhagen", "Oslo", "Paris"}
    capitals.remove("Washington")
except KeyError:
    print("This capital doesn't figure in the collection")

Consider the following code:

try:
    capitals = {"Stockholm", "Budapest", "Helsinki", "Copenhagen", "Oslo", "Paris"}
    y = 10 / 0
    print("About to remove Washington...")
    capitals.remove("Washington")
except KeyError:
    print("This capital doesn't figure in the collection")

Note how we inserted the 10 / 0 operation before Washington should be removed from the collection. That’s mathematically not possible and will throw an exception. We have an exception handling block so we should be safe, right? Run the code and…

Traceback (most recent call last):
File “C:/PythonProjects/HelloWorld/Various.py”, line 3, in
y = 10 / 0
ZeroDivisionError: division by zero

If you look at the output you’ll see that we never got to print(“About to remove Washington…”). The reason is that the exception was thrown at 10 / 0 and code execution was disrupted. The rest of the try-block won’t be executed. You’ll also see that this time another type of exception was thrown: ZeroDivisionError. However, we only have an exception handler for the KeyError type. That’s why the current except-block could not handle the ZeroDivisionError type.

That’s easy to remedy since you can have multiple except blocks for various exception types:

try:
    capitals = {"Stockholm", "Budapest", "Helsinki", "Copenhagen", "Oslo", "Paris"}
    y = 10 / 0
    print("About to remove Washington...")
    capitals.remove("Washington")
except KeyError:
    print("This capital doesn't figure in the collection")
except ZeroDivisionError:
    print("Errr..., what are you doing???")

This prints “Errr…, what are you doing???” on the screen. Code execution jumped from 10 / 0 to the ZeroDivisionError exception handling block.

We’ll continue in the next post.

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 58: exception handling in code

  1. Pingback: Python language basics 58: exception handling in code | Dinesh Ram Kali.

  2. Pingback: Python language basics 59: catching multiple exception types | 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

Elliot Balynn's Blog

A directory of wonderful thoughts

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: