Created
August 9, 2022 16:29
-
-
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
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
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 | |
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
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