Skip to content

Instantly share code, notes, and snippets.

@samukasmk
Created August 30, 2023 13:45
Show Gist options
  • Save samukasmk/575cbe9d3b1795e4db91d5434bae510f to your computer and use it in GitHub Desktop.
Save samukasmk/575cbe9d3b1795e4db91d5434bae510f to your computer and use it in GitHub Desktop.
Rasing multiple exception in Python Language
import traceback
# define some sample function with a nonexisting var
def my_function():
some_var = nonexisting_var
# create dict to store all raised exceptions
raised_exceptions = {}
# for 3 times execute a broken function (that generates execptions)
for execution_turn in range(0, 3):
try:
my_function(execution_turn)
except Exception as exc:
# store each exception with all traceback information
raised_exceptions[exc] = traceback.format_exc()
# if found exceptions in dict
if raised_exceptions:
# raise a father exception with all sub exceptions
raise Exception(raised_exceptions)
# $ python raise_multiple_exceptions.py
# Traceback (most recent call last):
# File "/your/folder/raise_multiple_exceptions.py", line 21, in <module>
# raise Exception(raised_exceptions)
# Exception: {
# TypeError('my_function() takes 0 positional arguments but 1 was given'): 'Traceback (most recent call last):\n File "/your/folder/raise_multiple_exceptions.py", line 13, in <module>\n my_function(execution_turn)\nTypeError: my_function() takes 0 positional arguments but 1 was given\n',
#
# TypeError('my_function() takes 0 positional arguments but 1 was given'): 'Traceback (most recent call last):\n File "/your/folder/raise_multiple_exceptions.py", line 13, in <module>\n my_function(execution_turn)\nTypeError: my_function() takes 0 positional arguments but 1 was given\n',
#
# TypeError('my_function() takes 0 positional arguments but 1 was given'): 'Traceback (most recent call last):\n File "/your/folder/raise_multiple_exceptions.py", line 13, in <module>\n my_function(execution_turn)\nTypeError: my_function() takes 0 positional arguments but 1 was given\n'
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment