'How to raise Exception with array?

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


Solution 1:[1]

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user2246849
Solution 2 Bastian Venthur