2015-11-08 53 views
0

我想將一些異常處理代碼整合到單個異常子句中,但由於exc_info缺少信息,我無法獲取所需的所有異常信息。如何從sys.exc_info中獲取自定義的異常詳細信息?

import sys 

class CustomException(Exception): 
    def __init__(self, custom_code): 
     Exception.__init__(self) 
     self.custom_code = custom_code 

try: 
     raise CustomException("test") 
# This is OK 
# except CustomException as ex: 
#  print "Caught CustomException, custom_code=" + ex.custom_code 
# But I want to be able to have a single except clause... 
except: 
     ex = sys.exc_info()[0] 
     if ex is CustomException: 
       # AttributeError: 'tuple' object has no attribute 'custom_code' 
       print "Caught CustomException, custom_code=" + ex.custom_code 

的總體思路是,除了子句中的代碼可以放在一個功能,任何人都可以通過捕捉除外只需調用。我正在使用Python 2.7。

+1

如果您希望能夠以不同的方式處理不同的異常類型,爲什麼要使用單個'except'子句?如果你想要一個'except'塊來處理幾個類型,你可以這樣做,除了(CustomException,IOError,KeyError)如:或者你想要的任何異常類型列表 –

+0

我希望其他人能夠擁有一個除了子句並調用我的錯誤處理程序來處理所有事情除了:dealWithIt()。 –

+0

該對象位於'sys.exc_info()[1]'中。 – tdelaney

回答

1

我不能重現你說你的代碼產生的錯誤。

除了推薦使用except:dealwithIt()之外,還有一個可怕的想法,因爲它會影響異常,下面是我認爲不需要的代碼。

import sys 

class CustomException(Exception): 
    def __init__(self, custom_code): 
     Exception.__init__(self) 
     self.custom_code = custom_code 

try: 
     raise CustomException("test") 

except: 
     ex_value = sys.exc_info()[1] 
     if isinstance(ex_value,CustomException): 
       print "Caught CustomException, custom_code=" + ex_value.custom_code 
+0

謝謝!正是我在找的東西。我不認爲這是一個可怕的想法。如果你有一堆方法正在做一些可能產生不同錯誤的東西,應該用一些額外的通用代碼來處理,再加上需要去捕捉所有東西,那麼這就避免了很多代碼重複(人們可能不會真正寫錯誤處理)。例如,在我的情況下,如果出現任何錯誤,我希望始終爲某些函數返回JSON HTTP響應。 –

+0

你可以通過明確地捕捉你的'CustomException'和'Exception'(除了'''''''',因爲它也捕獲'KeyboardInterrupt'和'SystemExit',你肯定不想要),並且可能會列出通用代碼在某些功能上 –

0

這就是你需要的。

import sys 

class CustomException(Exception): 
    def __init__(self, custom_code): 
     Exception.__init__(self) 
     self.custom_code = custom_code 

try: 
    raise CustomException("test") 

except Exception as e: 
    ex = sys.exc_info()[0] 
    if ex is CustomException: 
      # AttributeError: 'tuple' object has no attribute 'custom_code' 
      print "Caught CustomException, custom_code=" + e.custom_code 

ex = sys.exc_info()[0]在這種情況下ex指類CustomException作爲異常類型而不是例外的一個實例。