Goals: what you will make by the end of the day
- Know exception handling by using
- try …..except….else…..finally
- throw out exception with raise up something errors class
- Learning how to save and load JSON data
- Know how to avoid crashing our app by handling those errors
- Case study by using JSON format to improve our existing password manager and search email, password by website name and error handling
Catching Exceptions: The try catch except finally Pattern
Python 异常处理
Catch error exception then it doesn't have to fail, we can decide that something else should happen
try:
`#Something that might cause an exception`
except:
`#Do this if there was an exception`
else:
`#Do this if there were no exceptions`
finally
`#To do this no matter what happen`
#Simple exception handling
try:
file = open("a.txt")
a_dictionary = {"key":"value"}
print(a_dictionary["key"])
except FileNotFoundError:
print("file not found")
except KeyError as error_message:
print("Key not exist")
else:
context = file.read()
print(context)
finally:
file.close()
print("File was closed")
#Exception Handling
try:
file = open("b_file.txt")
a_dictionary = {"key": "value"}
print(a_dictionary["KEY"])
except **FileNotFoundError** as e:
print(f"File not found {e}")
#file = open("a_file.txt", "w")
#file.write("Something")
except KeyError as error_message:
print(f"The key {error_message} does not exist.")
else:
content = file.read()
print(content)
finally:
pass
#raise TypeError("This is an error that I made up.")
Raising your own Exception
- Note, for able to catch abnormal exception, we need specific Exception class to throw out
- when you raise up exception the following code won’t be executed
#BMI Example
#BMI Example
height = float(input("Height: "))
weight = int(input("Weight: "))
if height > 3:
**raise ValueError("Human Height should not be over 3 meters.")**
#raise Exception("Human Height should not be over 3 meters.")
bmi = weight / height ** 2
print(bmi)
[Interactive Coding Exercise] IndexError Handling
- Call function shall in try except block otherwise error handling will follow default error
try:
fruits = ["Apple", "Pear", "Orange"]
def make_pie(index):
fruit = fruits[index]
print(fruit + " pie")
**make_pie(4)**
except **IndexError** as e:
print(f"Fruit pie {e}")
[Interactive Coding Exercise] KeyError Handling