Calling a hook function every time an Exception is raised

后端 未结 4 1808
情深已故
情深已故 2020-11-30 10:05

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 c

4条回答
  •  生来不讨喜
    2020-11-30 10:46

    This code will not affect any exception classes that were created before the start of main, and most of the exceptions that happen will be of such kinds (KeyError, AttributeError, and so forth). And you can't really affect those "built-in exceptions" in the most important sense -- if anywhere in your code is e.g. a 1/0, the real ZeroDivisionError will be raised (by Python's own internals), not whatever else you may have bound to that exceptions' name.

    So, I don't think your code can do what you want (despite all the semicolons, it's still supposed to be Python, right?) -- it could be done by patching the C sources for the Python runtime, essentially (e.g. by providing a hook potentially caught on any exception even if it's later caught) -- such a hook currently does not exist because the use cases for it would be pretty rare (for example, a StopIteration is always raised at the normal end of every for loop -- and caught, too; why on Earth would one want to trace that, and the many other routine uses of caught exceptions in the Python internals and standard library?!).

提交回复
热议问题