Python Bootcamp Day 30 - 100 Days of Code by Dr Angela Yu
- Unusual Accountant
- Jan 8, 2022
- 2 min read

Day 30 Errors, Exceptions and Saving JSON Data
In the Day 30 lesson, I have learned the following things:
how to avoid crashing our app by handling errors
Particular data format called JSON - transferring data across the internet between applications
Search through the database in the password app we built.
Handling Errors & Exceptions
The types of errors we may encounter:
FileNotFoundError: the file name is not defined correctly.
KeyError: when trying to tap into a key that doesn't exist in a dictionary
IndexError: when trying to get hold of an index that doesn't exist in a list.
TypeError: we can't do anything with a particular type (e.g. str vs int).
In programming, we can catch these exceptions.
When dealing with exceptions:
try: executing something that might cause an exception
except: a block of code that you want the computer to exceute if there was an exception
else: do this if there were no exceptions
finally: carry out no matter what happens

If the file doesn't exist, the code line in except will be executed so it will create a new file.

We can also have multiple exceptions
#multiple exceptions
try:
file = open("a_file.txt")
a_dictionary = {"key": "value"}
print(a_dictionary["sdfa"])
except FileNotFoundError:
file = open("a_file.txt", "w")
file.write("something")
except KeyError as error_message:
print(f"There is a key error {error_message}")
We can get hold of the key that doesn't exist. This is a lot useful to catch where the key error comes from.

If there were no exceptions, it will jump to the else statement and the codes will be executed. If it catches an error, the else statement won't be triggered.
try:
file = open("a_file.txt")
a_dictionary = {"key": "value"}
print(a_dictionary["key"])
except FileNotFoundError:
file = open("a_file.txt", "w")
file.write("something")
except KeyError as error_message:
print(f"There is a key error {error_message}")
else:
content = open("a_file.txt", "r")
print(content)
Raising your own exceptions
When do you want to raise your own errors?
For example, if I'm calculating a person's BMI and the input for height should not be over 3 metres because human height cannot exceed 3 metres (fun fact: the tallest person in history was 9 feet, which is converted to approx. 2.7metres).
height = float(input("Height: "))
weight = int(input("Weight: "))
if height > 3:
raise ValueError("Human Height cannnot exceed 3 metres")
Comments