Home > Software engineering >  How to raise Exception with array?
How to raise Exception with array?

Time:05-08

I tried to throw an exception with array data:

 raise Exception([ValidateError.YEAR, row])

When I tried to catch it I get this error:

'Exception' object is not subscriptable

Code is:

    except Exception as e:
        #invalid
        print(e[0])

CodePudding user response:

To access the Exception arguments you passed as a list, you should use .args.

So, I believe you were looking for the following:

except Exception as e:
   #valid
   print(e.args[0][0])

As a side note, you can pass multiple arguments without them being in a list:

raise Exception(ValidateError.YEAR, row)

And then you need one index less:

except Exception as e:
   #also valid
   print(e.args[0])

CodePudding user response:

You can subclass Exception and implement the __getitem__ function like so:

class MyException(Exception):

    def __init__(self, l):
        self.l = l

    def __getitem__(self, key):
        return self.l[key]

try:
    raise MyException([1, 2, 3])
except MyException as e:
        print(e[0])

running it:

python3 main.py 
1
  • Related