第九章第3讲:finally
1. finally放在末尾
注意:无论是否发生异常,finally都会执行。
while True: try: x = int(input("Enter the first number:")) y = int(input("Enter the second number:")) print(x/y) except ZeroDivisionError: print("ZeroDivisionError") print("Please try again") except Exception as e: print("The invalid info is :" , e) print("Please try again") else: print("计算正确") break finally: print("This is end.")
函数中包含异常
def divede(x,y): try: result = x/y except ZeroDivisionError: print("ZeroDivisionError") except Exception as e: print(e) else: print("The result is ", result) finally: print("This is end.") print(divede(6,2)) print(divede(2,0)) print(divede("e",1))
2. 异常的传递(异常与函数)
1.函数中如果有发生异常的隐患,应该在函数中进行处理
2.如果调用某函数时存在异常的隐患,应该及时处理
def faulty(): raise Exception("something is wrong!") def ignore_exception(): faulty() def handle_exception(): try: faulty() except Exception as e: print(e) print(faulty()) print(ignore_exception()) # faulty中的异常传递到了ignore_exception中 print(handle_exception()) # handle_exception及时处理了faulty中的异常
3. if--else 与 try--except的效果
效率对比,可以忽略不计
def describePerson(person): print("Description of:", person["name"]) print("Age:",person["age"]) if "sex" in person: print("sex:",person["sex"]) else: print("sex doesn't exist.") dict = {"name":"Bela","age":13} dict1 = {"name":"Ann","age":13,"sex":"girl"} describePerson(dict) describePerson(dict1)
if方法要查找两次sex,1次是查看是否存在,第2次是获得值
try/except 可替换if方法,效率高,1次全部搞定
def describePerson(person): print("Description of:", person["name"]) print("Age:",person["age"]) try: print(("sex:") + person["sex"]) except KeyError: pass dicts = {"name":"Ann","age":13,"sex":"girl"} describePerson(dicts)