面试题答案
一键面试思路
- 在最外层使用
try - except
语句块来捕获所有异常。 - 利用
as
关键字获取异常实例,这样可以保留完整的异常信息。 - 可以根据异常类型进行不同的处理,或者统一记录异常信息。
代码示例
def inner_function1():
raise ValueError("This is a value error in inner_function1")
def inner_function2():
inner_function1()
def outer_function():
inner_function2()
try:
outer_function()
except Exception as e:
print(f"Caught exception: {type(e).__name__}, {e}")