A class with eventhandlers ?

R

Runsun Pan

Is it possible to code a class that raise exception
automatically when an error occurs?

We usually use try-except pair at where we expect an
error might occur. What am thinking is a class that
has built in error handling so we can do this:

c=MyClass()
c.onError = some_hook

or

c.onError('IndexError', IndexErrorHook)

or, more specific, a function/method-specific error
handling feature:

c.load.onError( IOErrorHook)
c.load( filename )

Is there such a mechnism around? If not, is it possible
to make such a thing ?

--
~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~
Runsun Pan, PhD
(e-mail address removed)
Nat'l Center for Macromolecular Imaging
http://ncmi.bcm.tmc.edu/ncmi/
~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~
 
A

Alex Martelli

Runsun Pan said:
or, more specific, a function/method-specific error
handling feature:

c.load.onError( IOErrorHook)
c.load( filename )

Is there such a mechnism around? If not, is it possible
to make such a thing ?

Never heard of one, but you could surely make a custom metaclass
satisfying your specs (==wrapping each method into an instance of a type
providing such an onError method, as well as a __call__ delegating to
the real method within a suitable try/except). Sounds like a lot of
work to me, though;-).


Alex
 
F

Farshid Lashkari

It's definitely possible, here's a small example. There are probably
better ways to do it, but I'll let you figure that out ;)

class ErrorHandler:
def __init__(self,method):
self.method = method
self.errorHook = None

def onError(self,hook):
self.errorHook = hook

def __call__(self, *args, **kwargs):
if self.errorHook:
try:
self.method(*args,**kwargs)
except Exception, e:
self.errorHook(e)
else:
self.method(*args,**kwargs)


class MyClass:
def __init__(self):
self.load = ErrorHandler(self.load)

def load(self,filename):
return self.x

def IOErrorHook(e):
print 'Caught error:',e

c = MyClass()
c.load.onError(IOErrorHook)
c.load('filename')
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,283
Messages
2,571,405
Members
48,098
Latest member
inno vation

Latest Threads

Top