12

Is there anyway to write an exception catch code that's compatible from python 2.4 to python 3?

Like this code:

# only works in python 2.4 to 2.7
try:
    pass
except Exception,e:
   print(e)

# only works in python 2.6 to 3.3
try:
    pass
except Exception as e:
    print(e)
1
  • 1
    A lot of projects maintain their code for python 2, and use 2to3 to automatically convert it to python 3 as necessary. That is usually easier than trying to write code that is compatible with both (this probably won't be the most difficult issue you come across). Commented Oct 1, 2012 at 23:51

1 Answer 1

17

Trying to write code that works in both Python 2 and Python 3 is ultimately rather futile, because of the sheer number of differences between them. Indeed, a lot of projects are now maintained in separate Python 2 and Python 3 versions as a result.

That said, if you're hell-bent on doing this in a super-portable way...

import sys
try:
    ...
except Exception:
    t, e = sys.exc_info()[:2]
    print(e)
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you nneonneo for your answer, and thank you @gnibbler for your tip :-)
@gnibbler: I believe it is..."The information returned is specific both to the current thread and to the current stack frame."
If you're using Logger classes (and really, you should be), you don't even need to import sys and use inscrutable code to print your exceptions - you can just call Logger.exception("message") or the class method logging.exception("message") and the exception message and/or stack trace will be included in the logger output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.