Goals: what you will make by the end of the day

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

#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

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