2015-11-08 48 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作为异常类型而不是例外的一个实例。