Error Handling in Python using With and Try

In this article we will discuss error handling using Python With Statements Try/Except/Finally statements, show how to use these in combination, and compare how it works to try/catch code blocks in other languages.

What is error handling?

Error handling is when you put in some extra code to tell your script what to do when things don’t go totally to plan. Perhps you try to open a file that isn’t there. Or perhaps a user puts in unexpected input.

Without any error handling, your program or script will simply crash, throw an error, and quit running. It is important to at least put in a minimal amount of error handling to ensure that your script/program will run reliably.

Try/Catch Statements

In many languages you use Try/Catch statmenets for error handling. In C# for example, you might write some code that looks like this:

The above code will attempt to read the txt file. If it cannot read the file, it will throw an exception. The catch codeblock then catches that exception into variable e. And uses the console.writeline method to print the exception onto the console. That way you can see what happened.

If you didn’t put in the try/catch blocks, the exception would hae still been shown on the screen, but the application would have crashed and you have had to re-launch it. Sometimes on your computer you might get an error about an uncaught exception right before your program closes. Those are cases like this one where the system.io.file.readalltext method was not in a try block of code.

Try/Exception/Finally Statements

Python does not have try/catch blocks. Instead python has try/exception blocks. They really do the same thing, but have different names.

Let’s look at a an example written in python:

In the above script, we start the try statement and we attempt to execute the code in that section. If it succeeds, it will print the text trying. It will then jump down to the finally section and print Finally! followed by “All Done” on the console.

If the above script is not able to open the test.txt file, it will throw an exception and print “FIddleSticks!” to the console, followed by Finally.

The next logical question about these statements are what are the roles of each section?

  • The Try code block is the code you really want to execute.
  • The Excepton code block is the bit of code that you want to execute in the event you get an error while executing the code in the try code block.
  • The Finally code block is code that you want to execute regardless of the outcome.

More helpful errors

You may find that simply writing fiddlesticks when you have an error is not all that helpful. You need to capture the error so you can write it to a log file, or maybe you want to display the error on the screen.

Lets try executing this code in our python script:

The above script will read test.txt and print the contents to the console. Unfortunately, if test.txt does not exist, you will get an error like this one:IOError: [Errno 2] No such file or directory: ‘test.txt’

Notice the type of error is IOError. That is helpful, because we can create an exception block of code specifically around IOErrors. Lets look at how we would write that code:

The above code will attempt to run what is in the try block. If it failes, with an IOError, it will run the code in the except block. In this case it will print out the error saying something about how it could not open or close a file. It will then run the finally code block when everything is finished.

Python With Statments

With statements can be used with try/catch statements to reduce the amount of code you need to write for handling different kinds of errors.

With statments call the __Enter__ and __Exit__ functions that are part of a given class. An example of this is with the File open class.

To properly handle errors when opening files, you would need some code similar to this:

Before we get into the with statements, lets examine this code a bit. In the previous secitons, we wrote some code to catch exceptions when opening a file. But the other issue is what happens if we have an issue after the file is already open. We need to make sure we close the file. We could put that in the finally section at the very bottom. But that will throw an exception if the original file never successfully opened. The result is this big mess of nested try/except statments to hopefully catch all of the different scenarios you may encounter.

Lucky for us, the makers of Python came out with a With Statement. Like I said previously, with with stamtent has a __enter__ and an __exit__ function that it calls at the beginning and the end of the statement. THis allows some of that code to be removed from the big try/except mess I demonstrated above. An example of a wtih statement can be seen below:

The above text will still thrown an exception if test.txt does not exist. However, we no longer have to remember to call f.close when we are all finished wih the file. If we do have the file open and an error occurs, the with statement will handle closing out the file handles for me. What this means is we can use the with statement in conjunction with our try/except code blocks to give us cleaner looking code. Let’s look at another example:

Notice the above example looks a lot like our original example. It is the same number of lines, and it is still very readable. However, it gives us similar functionality to the second example with the nested try/except loops.

%d bloggers like this: