Last active
August 29, 2015 14:11
-
-
Save x/dc57b27677c85d20becb to your computer and use it in GitHub Desktop.
Catch exceptions with context managers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ExceptionCatcher(): | |
def __enter__(self): | |
self.msg = None | |
def __exit__(self, type, value, traceback): | |
if type is Exception: | |
self.msg = value | |
return True # if you return a truthy value then the exception isn't raised | |
exception_catcher = ExceptionCatcher() | |
with exception_catcher: | |
raise Exception("hello world") | |
print exception_catcher.msg |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment