[ACCEPTED]-Calling a hook function every time an Exception is raised-exception

Accepted answer
Score: 19

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.

Score: 10

Your code as far as I can tell would not 23 work.

  1. __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__.

  2. Unfortunately 18 you can't change any of the attributes on 17 the Exception class. If that was an option you could 16 have changed Exception.__new__ and placed your hook there.

  3. 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 to import __builtin__; __builtin__.Exception = MyException

  4. Even if you changed __builtin__.Exception it will only affect 11 future uses of Exception, 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 over Exception.__subclasses__ and change the __bases__ for each 7 one of them to insert your Exception subclass there.

  5. 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 (think StopIterration).

I think that the only decent 2 way to do what you want is to patch the 1 Python sources.

Score: 7

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