简体   繁体   中英

Python compatibility: Catching exceptions

I have an application, that needs to be working in all "modern" Python versions, which means 2.5 - 3.2 . I don't want two code bases, so 2to3 is not an option.

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.

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 . The solution is to check 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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