[ACCEPTED]-Calling a hook function every time an Exception is raised-exception
If you want to log uncaught exceptions, just use 4 sys.excepthook.
I'm not sure I see the value of logging 3 all raised exceptions, since lots of libraries 2 will raise/catch exceptions internally for 1 things you probably won't care about.
Your code as far as I can tell would not 23 work.
__init__
has to return None and you are trying 22 to return an instance of backup exception. In 21 general if you would like to change what 20 instance is returned when instantiating 19 a class you should override__new__
.Unfortunately 18 you can't change any of the attributes on 17 the
Exception
class. If that was an option you could 16 have changedException.__new__
and placed your hook there.the 15 "
global Exception
" trick will only work for code in the 14 current module.Exception
is a builtin and if you 13 really want to change it globally you need 12 toimport __builtin__; __builtin__.Exception = MyException
Even if you changed
__builtin__.Exception
it will only affect 11 future uses ofException
, subclasses that have already 10 been defined will use the original Exception 9 class and will be unaffected by your changes. You 8 could loop overException.__subclasses__
and change the__bases__
for each 7 one of them to insert yourException
subclass there.There 6 are subclasses of
Exception
that are also built-in 5 types that you also cannot modify, although 4 I'm not sure you would want to hook any 3 of them (thinkStopIterration
).
I think that the only decent 2 way to do what you want is to patch the 1 Python sources.
This code will not affect any exception 23 classes that were created before the start 22 of main
, and most of the exceptions that happen 21 will be of such kinds (KeyError
, AttributeError
, and so forth). And 20 you can't really affect those "built-in 19 exceptions" in the most important sense 18 -- if anywhere in your code is e.g. a 1/0, the 17 real ZeroDivisionError will be raised (by Python's 16 own internals), not whatever else you may have 15 bound to that exceptions' name.
So, I don't 14 think your code can do what you want (despite 13 all the semicolons, it's still supposed 12 to be Python, right?) -- it could be done 11 by patching the C sources for the Python 10 runtime, essentially (e.g. by providing 9 a hook potentially caught on any exception 8 even if it's later caught) -- such a hook 7 currently does not exist because the use 6 cases for it would be pretty rare (for example, a 5 StopIteration
is always raised at the normal end of every 4 for
loop -- and caught, too; why on Earth would 3 one want to trace that, and the many other routine 2 uses of caught exceptions in the Python 1 internals and standard library?!).
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.