Skip to main content
Python 3

Python – Error handling with try

By April 12, 2013No Comments

In this tutorial we add to our project the final elements and that always seems to be error handling. The script works but we know the user base will just find every conceivable way to break the program and we have to, rather than want to add error handling. In Python 3 we use TRY, EXCEPT and FINALLY, real English words that have meaning and that is what Python is all about.

Our project script allows users to specify an input file, chances are they will misspell the file or perhaps use a file they do not have rights to, as well as a myriad of other issues they will invent. So before we open the file we can use:


then in the try block we can put the open method:


This way we are handling error and we can catch errors with:


Globally errors with the open method will be IOERRORs.

So we could use:

except IOERROR:
  print("Something went wrong")

This certainly is more tidy than leaving the error un-handled but we haven’t specified the error. Using the sys module we can examine the error and print the error text:

print(sys.exc_info() [0])

This way we can then handle errors more specifically, catch the permission errors and the file not found errors:

import sys
    f = open('/home/andrew/file1')
except FileNotFoundError:
    #print(sys.exc_info() [0])
    print("We could not find the file")
except PermissionError:
    print("You don't seem to have the rights to do that")
    print("An error undefined has occurred")
    print("Done error checking")

Anyway a little food for thought in your scripts, watch the video and see how you go….