Adapt exception handling to be compatible with both Python 2.7 and 3.x