Skip to content

Instantly share code, notes, and snippets.

@RomneyDa
Created August 3, 2022 19:25
Show Gist options
  • Save RomneyDa/894b05b19f16b35ddb80a4bfd7840d1f to your computer and use it in GitHub Desktop.
Save RomneyDa/894b05b19f16b35ddb80a4bfd7840d1f to your computer and use it in GitHub Desktop.
Python: approaches to handling multiple exceptions and doing something if any exception
class ExceptionA(Exception):
pass
class ExceptionB(Exception):
pass
class ExceptionC(Exception):
pass
values_to_test = ["A", "B", "C", "D"]
def do_something(value: str):
if value == "A":
raise ExceptionA
elif value == "B":
raise ExceptionB
elif value == "C":
raise ExceptionC
else:
print("No exceptions")
def do_on_any_error():
print("There was an exception")
# Approach 1: duplicate for each exception caught - 2 + 3*numExceptions lines
print("\n\nAPPROACH 1")
for value in values_to_test:
try:
do_something(value)
except ExceptionA:
print("Exception A")
do_on_any_error()
except ExceptionB:
print("Exception B")
do_on_any_error()
except ExceptionC:
print("Exception C")
do_on_any_error()
# Approach 2: get error in finally - 6 + 3*numExceptions lines
print("\n\nAPPROACH 2")
for value in values_to_test:
try:
do_something(value)
error = None
except ExceptionA as e:
print("Exception A")
error = e
except ExceptionB as e:
print("Exception B")
error = e
except ExceptionC as e:
print("Exception C")
error = e
finally:
if error:
do_on_any_error()
# Approach 3: boolean
# only works if not raising error or returning in excepts - 6 + 2*numExceptions lines
print("\n\nAPPROACH 3")
for value in values_to_test:
no_error = False
try:
do_something(value)
no_error = True
except ExceptionA as e:
print("Exception A")
except ExceptionB as e:
print("Exception B")
except ExceptionC as e:
print("Exception C")
if not no_error:
do_on_any_error()
# Approach 4: Catch all in the same except and check error type - 4 + 2*numExceptions lines
print("\n\nAPPROACH 4")
for value in values_to_test:
try:
do_something(value)
except (ExceptionA, ExceptionB, ExceptionC) as e:
if isinstance(e, ExceptionA):
print("Exception A")
if isinstance(e, ExceptionB):
print("Exception B")
if isinstance(e, ExceptionC):
print("Exception C")
do_on_any_error()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment