0

Is there any way to raise multiple exceptions in python? In the following example, only the first exception is raised.

l = [0]
try:
    1 / 0
except ZeroDivisionError as e:
    raise Exception('zero division error') from e

try:
    l[1]
except IndexError as e:
    raise Exception('Index out of range') from e

Is there any other way?

1
  • 2
    The only reason to raise an exception is to handle it and as the program stops with the first exception only it never reaches the 2nd or 3rd. But you can try collecting all of them in Array/Dictionary and return it to caller for logging. Commented Apr 13, 2023 at 12:07

3 Answers 3

1

Once an exception is raised and not catched, the execution of your program will stop. Hence, only one exception can be launched in such a simple script.

If you really want your program to raise multiple exceptions, you could however create a custom Exception representing multiple exceptions and launch it inside an except block. Example:

class ZeroDivAndIndexException(Exception):
    """Exception for Zero division and Index Out Of Bounds."""
I = [0]
try:
    1 / I[0]
except ZeroDivisionError as e:
    try:
        I[1]
        # Here you may raise Exception('zero division error')
    except IndexError as e2:
        raise ZeroDivAndIndexException()
Sign up to request clarification or add additional context in comments.

1 Comment

If you replace # Here you may raise Exception('zero division error') with raise Exception('zero division error') from e you will see an issue
0

Here my solution a bit long but seems to work :

class CustomError(Exception):
  pass

l = [0]
exeps = []
try:
  1 / 0
except ZeroDivisionError as e:
  exeps.append(e)
try:
  l[1]
except IndexError as e:
  exeps.append(e)

if len(exeps)!=0:
  [print(i.args[0]) for i in exeps]
  raise CustomError("Multiple errors !!")

Comments

-1
try:
    pass
except AttributeError:
    pass
except IndexError:
    pass

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.