【问题标题】:Python compatibility: Catching exceptionsPython 兼容性:捕获异常
【发布时间】:2012-05-13 01:20:09
【问题描述】:

我有一个应用程序,它需要在所有“现代”Python 版本中运行,这意味着 2.5-3.2。我不想要两个代码库,所以2to3 不是一个选项。

考虑这样的事情:

def func(input):
    if input != 'xyz':
        raise MyException(some_function(input))
    return some_other_function(input)

我怎样才能捕捉到这个异常,以访问异常对象? except MyException, e: 在 Python 3 中无效,except MyException as e: 在 Python 2.5 中无效。

显然,它可以返回异常对象,但我希望,我不必这样做。

【问题讨论】:

    标签: python exception-handling python-3.x compatibility python-2.5


    【解决方案1】:

    in the Py3k docs 已解决此问题。解决方法是查看sys.exc_info():

    from __future__ import print_function
    
    try:
        raise Exception()
    except Exception:
        import sys
        print(sys.exc_info()) # => (<type 'exceptions.Exception'>, Exception(), <traceback object at 0x101c39830>) 
        exc = sys.exc_info()[1]
        print(type(exc)) # => <type 'exceptions.Exception'>
        print([a for a in dir(exc) if not a.startswith('__')]) # => ['args', 'message']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-09
      相关资源
      最近更新 更多