Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an exception catching code works in Python2.4 to Python3

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)
like image 897
yegle Avatar asked Oct 01 '12 23:10

yegle


1 Answers

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)
like image 62
nneonneo Avatar answered Nov 15 '22 13:11

nneonneo