In previous articles we’ve seen how to read data from a file, or write data to a file in Python. This assumed everything was working, such as the file was there, and could be opened. But that won’t always be the case. In fact, there are a lot of types of errors that can occur in running an application, even more than just not being able to open a file.
So how do we handle those errors? Well in the old days, the program would just crash. Now we can use exceptions, and try to catch those errors and find a better solution to either exit “gracefully” or recover from the error.
An exception is the idea that normally a program will run this bit of code correctly, however, sometimes it might fail, we want to prepare for that.
The idea behind a exception, is a program pair of keywords called try/catch. Many languages have the idea of exceptions, and they all work basically the same way. You will be a section of code in the try block. The program will try to execute it. If it fails, you will catch the exception and handle it without bringing the system to its knees.
What you do in the catch block is often dependent upon what you are trying to catch, what the error might be, and what is possible. Many times you still end the program with an error, but hopefully a better, more useful error message than what Python normally gives you.
In Python the try block is literally try :. The catch is called except : and it follows all of the lines after the try block.
def main() :
try:
infile = open('names2.txt', 'r')
contents = infile.read()
infile.close()
print(contents)
except IOError:
print("An error occurred reading the file.")
print("Please make sure the file exists.")
main()
Error Types
Notice that after the except, it gave an error type. This allows us to check for a specific type of error, and write a message for it.
Two of the most common errors we’ll see are IOError, errors in reading and writing files. ValueError, errors in converting strings to numbers.
If we want, we can have an except without an error after it. This acts as a catch all, but can also make it harder to determine what error specifically occurred.
try :
... code
code ...
except :
print("An error occurred")
We have the ability to stack excepts, so there is more than one per try block. This allows us to catch multiple errors within the try.
try :
... code
code ...
except IOError :
print("ERROR: Could not open file...")
except ValueError :
print("ERROR: converting values to numbers.")
except :
print("ERROR: Some unexpected error occurred.")
Default Error Message
While I don’t usually recommend sending the default error message, you always can. It could be helpful to write to log files, but we’ll keep it simple for this next example.
except Exception as err :
print(err)
The as err, defines the exception occurring as a variable that we can use.
Else Clause
The else clause is optional. The block after it is called the else suite, and they are run, only if no exceptions were raised within the try block.
Finally Clause
The block of code runs after everything else. It is optional, and must appear last of all of the blocks written.
It’s main purpose is to do things like close files that might have been opened, so they are not corrupted, or handle other sensitive things like that. It runs after any exception code runs.
Exceptions in Python was originally found on Access 2 Learn