4thSpace 4thSpace - 1 year ago 72
Python Question

Why does custom exception string print as array?

In Python 2.7.x, I've created an Exception class:

class myException(RuntimeError):
def __init__(self,arg):
self.args = arg

When I use it:

raise myException("This is a test")
except myException as e:
print e

It prints out like this:

('T', 'h', 'i', 's', ' ', 'i', 's'...)

I didn't print the whole thing but why isn't this printing out as a string? And how do I convert it?

Also, why is e.message blank?

Answer Source

args on an exception is special; it expects to be a sequence. Assigning a string to self.args is legal, it is a sequence, but it is converted to a tuple when you do.

Assign a tuple containing your argument instead:

class myException(RuntimeError):
    def __init__(self, arg):
         self.args = (arg,)

See the BaseException documentation:

The tuple of arguments given to the exception constructor. Some built-in exceptions (like IOError) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download