Exceptional Monkey Patching class and other built-in classes

Regardless of the type of Excetchion, I would like to print a message whenever an exception occurs.

I tried the following:

class MyException(BaseException):
  def __init__(self, msg):
    super(BaseException, self).__init__(msg)
    print "Howdy", msg

__builtins__.Exception = MyException

try:
  raise IOError("world")
except Exception as e:
  pass

I expected the "Howdy world" to print, but instead I get nothing.

EDIT:

@helmut suggested using sys.settrace, the following code works as expected.

import sys

def trace(frame, event, arg):
    print event
    return trace

sys.settrace(trace)

def foo():
    raise Exception()

def bar():
    foo()

def baz():
    try:
        bar()
    except:
        pass

baz()

exit()

Too bad it is too slow for my use.

+4
source share
1 answer

Why not a monkey patch?

, . , MyException - Exception, , Exception . , , . . IOError, . , Exception, . , __init__ __new__. , , :

TypeError: can't set attributes of built-in/extension type 'exceptions.Exception'

, , , .

:

, sys.settrace. , . , - 'exception'. , , , .

+5

Source: https://habr.com/ru/post/1530154/


All Articles