每次引发异常时调用钩子函数 [英] Calling a hook function every time an Exception is raised

查看:100
本文介绍了每次引发异常时调用钩子函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我希望能够在程序中任何地方发生任何异常时都能够登录到文件。我不想修改任何现有代码。

Let's say I want to be able to log to file every time any exception is raised, anywhere in my program. I don't want to modify any existing code.

当然,这可以概括为每次引发异常时都可以插入钩子。

Of course, this could be generalized to being able to insert a hook every time an exception is raised.

以下代码是否被认为可以安全地进行此类操作?

Would the following code be considered safe for doing such a thing?

class MyException(Exception):

    def my_hook(self):
        print('---> my_hook() was called');

    def __init__(self, *args, **kwargs):
        global BackupException;
        self.my_hook();
        return BackupException.__init__(self, *args, **kwargs);


def main():
    global BackupException;
    global Exception;

    BackupException = Exception;
    Exception = MyException;

    raise Exception('Contrived Exception');


if __name__ == '__main__':
    main();


推荐答案

如果要记录未捕获例外,只需使用 sys.excepthook

If you want to log uncaught exceptions, just use sys.excepthook.

我不确定我是否记录了记录 all 引发异常的价值,因为许多库将在内部引发/捕获异常,而这可能是您不会关心。

I'm not sure I see the value of logging all raised exceptions, since lots of libraries will raise/catch exceptions internally for things you probably won't care about.

这篇关于每次引发异常时调用钩子函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆