Skip to main content

Python quick bite 04: Catching exceptions

So far whenever we face an error message after running our code, we just took it back to reading the code line by line and trying to resolve them. However, when our codes become more and more complex, possibly with thousands of lines (dreaming about that since I am still a beginner), it will get harder to do that. 
Here is the python syntax to help us capture these exceptions so that we know possibly where our codes had gone wrong and so how to resolve them and in some cases still allow the code to proceed.

try: something that might cause an exception
except: do this if there was an exception
else: do this if  there were no exceptions
finally: do this no matter what happens

    file = open("a.txt") 
    # this will not work if there is no existing file. 

except FileNotFoundError   
#if there is nothing after except, then when the codes in the try clause fails, it will just move to the 
#except clause. If there is more than one error happening in the try clause, it will not picked out and
#therefore it is safer to add in the particular error to be captured and this case it is FileNotFoundError.
    file = open("a.txt","w")
    file.write("If there is no a.txt file, using write mode will ensure the file is created instead. We perform     this write to show that this clause under except is executed.")

    content =
#this set of code will not run in the first run since there is no a.txt file and the except clause is run to 
#create that file as well as write to it. On the second run of code, since a.txt is created, there is no 
#exception and else clause is executed and the contents will be written in the except clause will be 

    print("File was closed.")
#it is good to place codes here that we want to perform no matter what such as to close the file after 
#opening it. Angela mentioned that finally is not commonly used but let's keep it in mind for when we 
#have codes to run no matter what happens. 

We can also add in a lot of exception clauses to capture all the codes in the try clause.

Here are other exception errors to capture. 

eg KeyError
daily_account= [
{"save": 10, "use": 5}, 
{"save": 25, "use": 60}, 
{"use": 5}, 
{"save": 3}, 
{"save": 5, "use" : 10} 
#let's say we have a daily account dictionary but not every day we had recorded save or use money
#now we want to total up the amount saved.

total_save = 0
for entry in daily_account:
        total_save += entry['save']
    except KeyError:
        total_save += 0

output: 43
In this case whenever there is no save entry, I added 0 to the total_save. You can also use pass to just skip that entry whenever there is no save entries. 

eg IndexError
abc_list = ["a", "b", "c", "d"]
def alphabet(index): #return the selected alphabet in the list.
        letter = abc_list[index]
    except IndexError:

output: abcd
#cos index 4 is out of the range and the except clause is activated.
output: c
#index 2 give letter which is then printed out. 

eg TypeError

text = "hello"
number = 9
    print(text + number)
    #this is not possible as we cannot add a string and an integer
except TypeError:
    print(text + str(number))

We can also create an error message using raise to capture inaccurate user inputs rather than proceeding through with the codes. 

eg raising errors
height = float(input("Height: "))
weight = int(input("Weight: "))

if height > 3:
    raise ValueError("Human height should not be over 3 meters.")

bmi = weight / height **2
#if user key in height above 3, it will generate a error with the error message and the code will not proceed to give it an unrealistic bmi.