Dave Halter
Dave Halter

Reputation: 16325

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.

Upvotes: 4

Views: 135

Answers (1)

Brian Gesiak
Brian Gesiak

Reputation: 6958

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']

Upvotes: 5

Related Questions