简体   繁体   English

Python兼容性:捕获异常

[英]Python compatibility: Catching exceptions

I have an application, that needs to be working in all "modern" Python versions, which means 2.5 - 3.2 . 我有一个应用程序,需要在所有“现代”Python版本中工作,这意味着2.5 - 3.2 I don't want two code bases, so 2to3 is not an option. 我不想要两个代码库,所以2to3不是一个选项。

Consider something like this: 考虑这样的事情:

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

How can I catch this exception, to get access to the exception object? 如何捕获此异常,以获取对异常对象的访问权限? except MyException, e: is not valid in Python 3, and except MyException as e: is not valid in python 2.5. except MyException, e:在Python 3中无效, except MyException as e:在python 2.5中无效。

Clearly it could have been possible to return the exception object, but I hope, i don't have to do this. 显然,它本可以返回异常对象,但我希望,我不必这样做。

This concern is addressed in the Py3k docs . 这个问题在Py3k文档中得到了解决 The solution is to check sys.exc_info() : 解决方案是检查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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM