Handling errors & Exceptions
#File Not Found
with open("a_file.txt") as file:
file.read()
#KeyError
a_dictionary = {"key": "value"}
value = a_dictionary{"non_existent_key"}
#IndexError
fruit_list = ["Apple", "Banana", "Pear"}
fruit = fruit_list[3]
#TypeError
text = "abc"
print(text + 5)
Catching Exceptions
- 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 Not Found
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"That key {error_message} does not exist.")
else:
content = file.read()
print(content)
finally:
file.close()
print("File was closed")