Home > front end >  Raising multiple exception in python
Raising multiple exception in python

Time:06-29

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?

CodePudding user response:

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

CodePudding user response:

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