Kingston X
Kingston X

Reputation: 109

Raising multiple exception in python

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?

Upvotes: 0

Views: 1127

Answers (3)

pedagil
pedagil

Reputation: 21

try:
    pass
except AttributeError:
    pass
except IndexError:
    pass

Upvotes: -1

Lucas Meier
Lucas Meier

Reputation: 469

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()

Upvotes: 1

Virgaux Pierre
Virgaux Pierre

Reputation: 205

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 !!")

Upvotes: 0

Related Questions