| 3 | """ An exception handling idiom using decorators""" |
| 4 | |
| 5 | def wrapper(f): |
| 6 | if pargs: |
| 7 | (handler,li) = pargs |
| 8 | t = [(ex, handler) |
| 9 | for ex in li ] |
| 10 | t.reverse() |
| 11 | else: |
| 12 | t = [(Exception,None)] |
| 13 | |
| 14 | def newfunc(t,*args, **kwargs): |
| 15 | ex, handler = t[0] |
| 16 | |
| 17 | try: |
| 18 | if len(t) == 1: |
| 19 | f(*args, **kwargs) |
| 20 | else: |
| 21 | newfunc(t[1:],*args,**kwargs) |
| 22 | except ex,e: |
| 23 | if handler: |
| 24 | handler(e) |
| 25 | else: |
| 26 | print e.__class__.__name__, ':', e |
| 27 | |
| 28 | return functools.partial(newfunc,t) |
| 29 | return wrapper |
| 30 | def myhandler(e): |
| 31 | print 'Caught exception!', e |