Adding Data to an Exception in Python

Viewed 892

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.

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)

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
Related