1

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:

try:
  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?

1
  • Have you tried def __init__(self,*arg): (note the star)? Commented Mar 11, 2017 at 18:35

2 Answers 2

5

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:

args
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.

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

Comments

1

All you have to do is:

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

Comments

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.