我有一個函數,我的原因異常,我希望它是一個裝飾器。其代碼如下:如何捕捉裝飾器中的異常
def des(i):
def new_func(func):
if i == 1:
raise Exception
else:
return func
return new_func
@des(1)
def func():
print "!!"
if __name__ == '__main__':
try:
func()
except Exception:
print 'error'
但輸出是:
Traceback (most recent call last):
File "D:/des.py", line 10, in <module>
@des(1)
File "D:/des.py", line 4, in new_func
raise Exception
Exception
這樣,我怎麼能捕獲此異常?
我認爲這可能與您的問題有關:[捕獲裝飾器中的異常,同時允許調用者捕獲異常](http://stackoverflow.com/questions/4249939/how-do-i-catch-an-exception -in-a-decorator-but-allow-the-caller-catch-it-w-rq = 1) – user2412092
它的工作原理,我明白它是如何工作的。謝謝:) – LiGa