Python language basics 58: exception handling in code
October 24, 2015 2 Comments
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.
Pingback: Python language basics 58: exception handling in code | Dinesh Ram Kali.
Pingback: Python language basics 59: catching multiple exception types | Dinesh Ram Kali.