捕获异常是为了程序遇到异常时能处理异常同时接着向下运行,但这样无法看到引发异常的位置
def divide(a, b):
try:
return a / b
except ZeroDivisionError as e:
print(e)
return "分母为0"
if __name__ == "__main__":
print(divide(1, 1))
print(divide(1, 0))
# 1.0
# division by zero
# 分母为0
try:
具体代码
except Exception as e:
import traceback
traceback.print_exc()
效果
def divide(a, b):
try:
return a / b
except ZeroDivisionError as e:
import traceback
traceback.print_exc()
return "分母为0"
if __name__ == "__main__":
print(divide(1, 0))
'''
Traceback (most recent call last):
File "D:/code/test/test4.py", line 3, in divide
return a / b
ZeroDivisionError: division by zero
'''