Reputation: 435
I want to change the behavior of unhandled Exceptions (all of them) in python to send emails without changing code very much or using special error handlers everywhere.
My hope is to subclass Exception and then redefine it at the beginning of a given module.
So the subclassing is here:
class ExceptionMailer(Exception):
def __init__(self, m):
self.message = m
send_email(email_address,self.message)
Then at the at the begining of a module I can do this:
Exception = ExceptionMailer
Then when an Exception is raised an email with it's message is sent. I have gotten this to work strictly for Exception
but not for say ValueError
. My hope was that redefining Exception
would redefine all the error types but I was clearly wrong. Is what I am trying to do possible?
Upvotes: 1
Views: 485
Reputation: 288298
I want to change the behavior of Exceptions (all of them) ...
No, you don't. In Python, exceptions are used for flow control. For example, your handler would fire every time a StopIteration
is raised, or a comparison function fails, or a library uses an exception to signal something.
Instead, simply wrap your code in
try:
# ... large block of code
except BaseException as e:
send_email(email_address, e.message)
Upvotes: 1
Reputation: 29747
In the moment you redefine Exception
, all its subclasses were created, so it doesn't affect them:
>>> class A(object):
def a(self):
print 'a in A'
>>> class B(A):
pass
>>> B().a()
a in A
>>> class C(object):
def a(self):
print 'a in C'
>>> A = C
>>> B().a()
a in A
Regarding your problem. Take a look at sys.excepthook
. It allows you to redefine program behavior in case of any uncaught exception.
Upvotes: 2