Better exception handling to be more compatible with Python versions > 2.6