Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active April 28, 2022 02:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CMCDragonkai/08266b1463158f4156f66d4bf077add6 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/08266b1463158f4156f66d4bf077add6 to your computer and use it in GitHub Desktop.
Raising, Reraising and Chaining Exceptions in Python #python
#!/usr/bin/env python
# if you are handling an exception, you can raise another exception in 4 ways:
# EXCEPTION RERAISE/RETHROW
# this reraises the same exception, in this case
# it just means you couldn't handle the exception
try:
raise Exception
except Exception as e:
raise e
# raise # this is equivalent and you won't need to bind the exception
# EXCEPTION HANDLING EXCEPTION
# this raises another exception in the handling of the first exception
# python will recognise this and report it as so
# only do this if you really have an exception while handling an exception
try:
raise Exception
except Exception as e:
raise Exception
# EXCEPTION OVERRIDE
# this overrides the exception with a whole new exception
# use this when you are wrapping a library of internal exceptions and presenting a transformed external exceptions
try:
raise Exception
except Exception as e:
raise Exception from None
# EXCEPTION CHAIN
# this raises a new exception and chains the new exception with the old exception
# use this when your code represents an onion of different layers each capable of handling different exceptions
try:
raise Exception
except Exception as e:
raise Exception from e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment