异常统一捕获
继承自Motor类,可实现python代码在任何地方抛出异常都能被捕获并记录,避免程序异常退出时没能记录现场。
1 from abc import abstractmethod, ABC
2 import traceback 3 class Motor(ABC): 4 @abstractmethod 5 def customize(self)->int: 6 pass
7 @abstractmethod 8 def destroy(self): 9 pass 10 11 @abstractmethod 12 def handle_exception(self, exp, msg): 13 #log.info(msg) 14 15 @abstractmethod 16 def run(self): 17 ret = 1
try:
ret = self.customize()
except Exception as e:
msg = traceback.format_exc()
self.handle_exception(e, msg)
finally:
self.destroy()
exit(ret)
class MyMotor(Motor):
#实现除run以外的其他函数
m = MyMotor()
m.run()