9

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.

0

2 Answers 2

8

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)

Sign up to request clarification or add additional context in comments.

1 Comment

He shows exactly what he wants to do with the second argument: save it for later use. (In the example, it would be available as me.numb.)
8

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

2 Comments

You actually might put this under your original question below a separator like: --------- UPDATE --------- PS - glad it works, I didn't actually test it and figured it had a typo
@AdamHughes I wondered about that, but it seemed to me that it would confuse people to see an answer under the question. I imagined they would stop reading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.