The Python Try Statement: An Introduction

phythonTryIt’s a fact of life in programming: mistakes happen. We don’t mean the bugs that you will catch and fix as part of developing the program. We’re talking here about the unexpected problems that will happen when your program is out in the real world. Someone enters data that results in division by zero. Your program requires a file, but it has been deleted from the hard drive. Those pesky users! If it wasn’t for them, programs would run perfectly.

Not to worry, help is at hand. The Python try statement provides a way to catch these problems and allow the program to proceed normally. Get a start on Python programming with this course for beginners. If you already know another programming language, try this course for more experienced programmers.

First, let’s get clear on what we are trying to cure here. In Python, exceptions are smaller problems that can be defined and that probably have solutions. Programs can handle and recover from exceptions. Errors are larger scale problems that are so catastrophic that it is best to abort the program. The Python try statement is meant to deal with exceptions. Some examples of exceptions are:

Division by zero

Attempting to do arithmetic with a string variable

Calling a method that does not exist

Opening a file that does not exist

Opening a file for writing when the system has marked it read-only

Pressing the keyboard combination that stops execution

Exceptions pose two problems. First is the obvious problem that the program cannot function as intended. The other problem is that the user must be made aware that something is wrong. The default messages that Python generates on exceptions are cryptic and may not appear prominently enough to get the user’s attention. If the user is informed that the file is read-only, they may be able to fix that, and the program can be re-run successfully.

Simple Example: Division by Zero

Python allows you to handle exceptions with the try-except block statement. Code that might generate an exception is placed within this block. Here’s an example:

code that asks user for values of a and b

code that reads the response and assigns them to the variables a and b

try:

c = a/b

except ZeroDivisionError:

print “you tried to divide by zero”

In this case we anticipate that someone might put in a zero for b and cause an error. The statement is put in the try portion of the block. The except keyword, in this case, is defined for the specific error we expect, and a message is printed. It runs only if the exception occurred. The program has halted gracefully in a manner that lets the user know what is wrong, so they can correct it. You can make the message even more obvious by putting it in a GUI message box. You can take a course on Python GUIs to learn more.

But wait. The silly user may have put in a letter or a special character instead of a number for a or b. This will not trigger the except clause we wrote. We need to have another except clause to handle this:

code that asks user for values of a and b

code that reads the response and assigns them to the variables a and b

try:

c = a/b

except ZeroDivisionError:

print “you tried to divide by zero”

except TypeError:

print “one of the items you entered was not a number”

except:

print “there is an unknown problem with a value you entered”

Note that we have also included a “naked” except statement. This will be triggered by any other exception we haven’t covered.

Now suppose that we want to let the user know that the input of a and b is good, no exceptions were thrown. We can do that with an else clause. The else clause is executed only if no exceptions are encountered:

code that asks user for values of a and b

code that reads the response and assigns them to the variables a and b

try:

c = a/b

except ZeroDivisionError:

print “you tried to divide by zero”

except TypeError:

print “one of the items you entered was not a number

except:

print “there is an unknown problem with a value you entered”

else:

print “the input is good”

There is a form of the except statement that allows you to specify more than one error to be handled by the same code. It will be triggered by any of the errors listed:

Except (er1, er2):

code to handle these exceptions

Better Example: Putting It All Together

Now let’s go on to a more realistic example. Suppose we are opening a file, perhaps a database, and writing data to it. There are some potential exceptions that can happen. Suppose such an exception happens after the file is opened. Our try-except block can handle the situation. See this article for more on working with files in Python.

try:

code to open a file for writing

code to process data and write to the file

code to close the file

except:

code to handle all exceptions

We have a problem here. If there is an exception before the file is closed, execution of the program jumps to the except clause, performs the code, and then continues on. The file is never closed. We need a way to guarantee that the file is closed, no matter what happens. This is done with the finally clause:

try:

code to open a file for writing

code to process data and write to the file

except:

code to handle all exceptions

finally:

code to close the file

We move the code that closes the file to the finally clause. The code in this section runs whether or not there is an exception.

As of Python version 2.5, all of these clauses can be put into one block. Suppose an exception occurs in our data, and it should not be written to the file. We can include an else clause that writes the data. The else clause will only execute if there have been no exceptions.

try:

code to open a file for writing

code to process data

except:

code to handle all exceptions

else:

code to write the data to the file

finally:

code to close the file

This should give you a good start on how to use the Python try statement. As you can imagine, there are many more advanced ways this can be used. Now go to the next level with an intermediate course in Python.