2012-12-17 91 views
0

下面我有一個代碼示例,在這裏我想捕捉一些例外:Python中嵌入的異常處理

在主函數

try: 
    ... 
    do_something() 
except some_exception,e: 
    do_some_other_thing 

do_something功能

try: 
    ... 
except some_exception,e: 
    do_some_other_thing 

所以當我測試它時,我發現異常處理了兩次(一次在do_somthing(),一次在main函數中),這是我的觀察結果吃什麼好?

有沒有辦法來捕捉異常,只有它的功能沒有捕獲?因爲有兩種情況我想要捕捉,它們有時被包裝到相同的異常處理類中(即some_exception

回答

1

您的觀察結果不準確;必須有兩個地方提高some_exeption,或者你明確地重新提高它。

一旦正確捕獲到異常,它將不會被堆棧中更高層的其他處理程序捕獲。

這是最簡單的顯示一個小演示:在調用

>>> try: 
...  try: 
...   raise AttributeError('foo') 
...  except AttributeError as e: 
...   print 'caught', e 
... except AttributeError as e: 
...  print 'caught the same exception again?', e 
... 
caught foo 

只有except處理程序。如果,在另一方面,我們重新拋出異常,你會看到兩個處理器打印一條消息:

>>> try: 
...  try: 
...   raise AttributeError('foo') 
...  except AttributeError as e: 
...   print 'caught', e 
...   raise e 
... except AttributeError as e: 
...  print 'caught the same exception again?', e 
... 
caught foo 
caught the same exception again? foo 

因此,沒有必要非得處理「是不被捕獲的異常功能';你只需要需要處理那些之前沒有捕獲到的異常。

1

爲什麼不試試看看簡單測試會發生什麼?

def main(): 
    try: 
     raise ValueError("in main!") 
    except ValueError as e: 
     print "caught exception",str(e) 
     #for fun, re-run with the next line uncommented and see what happens! 
     #raise 

try: 
    main() 
except ValueError: 
    print "caught an exception above main" 

如果你真正嘗試這個代碼,你會發現,只打印一個消息(該main函數內)證明的異常不會向上傳播一旦被抓(除非你重新raise它在你的除了條款)。