python捕获异常装饰器_如何在装饰器中捕获异常,但是允许调用者也可以捕获它?...

I have a python function that may raise an exception. The caller catches the exception and deals with it. Now I would like to add a decorator to that function that also catches the exception, does some handling, but then re-raises the exception to allow the original caller to handle it. This works, except that when the original caller displays the call stack from the exception, it shows the line in the decorator where it was re-raised, not where it originally occurred. Example code:

import sys,traceback

def mydec(func):

def dec():

try:

func()

except Exception,e:

print 'Decorator handled exception %s' % e

raise e

return dec

@mydec

def myfunc():

x = 1/0

try:

myfunc()

except Exception,e:

print 'Exception: %s' % e

type,value,tb = sys.exc_info()

traceback.print_tb(tb)

The output is:

Decorator handled exception integer division or modulo by zero

Exception: integer division or modulo by zero

File "allbug.py", line 20, in

myfunc()

File "allbug.py", line 9, in dec

raise e

I would like the decorator to be able to handle the exception but the traceback should indicate the x = 1/0 line rather than the raise line. How can I do this?

解决方案

Just use raise; (i.e. do not raise anything specific, just raise;) in a catch block to re-raise the exception without "resetting" the traceback.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值