Improved exception handling in __exit__