Calling a hook function every time an Exception is raised

后端 未结 4 1809
情深已故
情深已故 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 11:00

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

    1. __init__ has to return None and you are trying to return an instance of backup exception. In general if you would like to change what instance is returned when instantiating a class you should override __new__.

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

    3. the "global Exception" trick will only work for code in the current module. Exception is a builtin and if you really want to change it globally you need to import __builtin__; __builtin__.Exception = MyException

    4. Even if you changed __builtin__.Exception it will only affect future uses of Exception, subclasses that have already been defined will use the original Exception class and will be unaffected by your changes. You could loop over Exception.__subclasses__ and change the __bases__ for each one of them to insert your Exception subclass there.

    5. There are subclasses of Exception that are also built-in types that you also cannot modify, although I'm not sure you would want to hook any of them (think StopIterration).

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

提交回复
热议问题