RSS Feed

RSS
Comments RSS

Python – being exceptional!

One of the key features of Python that often gets overlooked is its ability to deal with exceptions, which is any time a piece of program code could throw a system or runtime error and end abnormally.

The construction that Python provides to handle these situations is the try:/except: combination. The idea is that you have a piece of code that has a high likelihood of creating an error, also call “throwing an exception”. This portion of the code is put in the try: section. If the first piece of code executes normally, without error, the program continues normally. If it traps an exception, then the code in the except: section is executed. In this way, the program continues one way or another in the event of the expected error. This finds its use very often in file handling code where a file open request might fail.

Here is an example. Also, this demonstrates how to do some work in SQLite3 (might as well get two useful examples for the price of one, right?). In this case it is not a file error that is being watched for by the exception handling code, but instead a runtime error that would be created by trying to add a table to a database if the table already exists.

#Create anSQLite3 database.
connection = sqlite3.connect(‘parts.db’) #If the database does not already exist, it is created.
cursor = connection.cursor() #Create an instance of the database cursor.

#Try to create the table “myparts” in the parts.db database. If the table already exists, print an appropriate error message rather than crashing the program with an error and continue with the program.

try:
cursor.execute(‘CREATE TABLE myparts(id INTEGER PRIMARY KEY, part_number VARCHAR(16), part_desc VARCHAR(50), part_type VARCHAR(12))’)
except:
print(“DB already exists”)









*