Fix exception handling to support different Python versions.