Python中使用装饰器捕获异常
1.装饰器的编写
# 捕获异常装饰器
def catch_except(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
serror_info = traceback.format_exc()
log.error(serror_info)
msg_box = QMessageBox(QMessageBox.Warning, '报错', serror_info)
msg_box.show()
msg_box.exec_()
return 'countError'
return wrapper
2.装饰器的使用
正常代码
@catch_except
def normal_test():
a = 1/ 1
return a
result = normal_test()
print(result)
异常代码
@catch_except
def error_test():
a = 1/ 0
return a
result = error_test()
print(result)