Skip to content

Instantly share code, notes, and snippets.

@x
Last active August 29, 2015 14:11
Show Gist options
  • Save x/dc57b27677c85d20becb to your computer and use it in GitHub Desktop.
Save x/dc57b27677c85d20becb to your computer and use it in GitHub Desktop.
Catch exceptions with context managers
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