Skip to content

Instantly share code, notes, and snippets.

@shreve
Created August 9, 2022 16:29
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 shreve/8ce7b489c66d106872317df8834daa38 to your computer and use it in GitHub Desktop.
Save shreve/8ce7b489c66d106872317df8834daa38 to your computer and use it in GitHub Desktop.
A simple demo of the ordering of try/except/else/finally in python
testing dont_raise
try
else
finally
testing raise_known
try
except KnownException
finally
testing raise_unknown
try
Traceback (most recent call last):
File "try_except_else_finally_demo.py", line 17, in test_func
func()
File "try_except_else_finally_demo.py", line 40, in raise_unknown
raise UnknownException()
UnknownException
finally
import sys
import traceback
class KnownException(Exception):
"""This is the exception we expected"""
class UnknownException(Exception):
"""This is NOT the exception we expected"""
def test_func(func):
print(f"testing {func.__name__}")
try:
print("try")
func()
except KnownException as err:
print(f"except {err.__class__.__name__}")
except ValueError:
print("except ValueError")
except Exception as err:
print("".join(traceback.format_exception(err, err, err.__traceback__)))
else:
print("else")
finally:
print("finally")
print()
def dont_raise():
pass
def raise_known():
raise KnownException()
def raise_unknown():
raise UnknownException()
def main():
test_func(dont_raise)
test_func(raise_known)
test_func(raise_unknown)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment