Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Data to an Exception in Python

I'm trying to create an exception that contains the typical string and an additional piece of data:

class MyException(RuntimeError):
    def __init__(self,numb):
        self.numb = numb

try:
    raise MyException("My bad", 3)
except MyException as me:
    print(me)

When I run the above I get the obvious complaint that I've got only two arguments in __init__ but I passed three. I don't know how to get the typical string into my exception and add data.

like image 934
Ray Salemi Avatar asked May 14 '26 14:05

Ray Salemi


2 Answers

You can pass the first arg (arg1) into the parent exception's constructor and then do what you want with the second argument.

class MyException(RuntimeError):
    def __init__(self, arg1, arg2):
        super().__init__(arg1)
        print("Second argument is " + arg2)

Note - if using Python 2, the call to super() is replaced by super(MyException, self)

like image 182
Adam Hughes Avatar answered May 17 '26 04:05

Adam Hughes


The updated code based on the answer above looks like this:

class MyException(RuntimeError):
    def __init__(self,message,numb):
        super().__init__(message)
        self.numb = numb

try:
    raise MyException("My bad", 3)
except MyException as me:
    print(me)
    print(me.numb)

It outputs

    My bad
    3
like image 24
Ray Salemi Avatar answered May 17 '26 02:05

Ray Salemi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!