How can I fix the error in my custom Python exception class?

  • Context: Python 
  • Thread starter Thread starter tigger88
  • Start date Start date
  • Tags Tags
    Python
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 4K views
tigger88
Messages
17
Reaction score
0

Homework Statement


For an introductory Python course, one of the problems I am required to do involves creating a MyError class that inherits from Exception. Its purpose is to handle possible wrong inputs to the int() function and to return an error statement that includes what was input.

I have spent AGES on this (far too long) and finally have something that is semi-functional. Currently, however, I get an error saying "MyError: <unprintable MyError object>.

I think it's caused by the def __init__ method but I don't know how to fix it.
2. The attempt at a solution
Here is my code:
import exceptions
class MyError(Exception):
def __init__(self,value):
Exception.__init__(self,value)
self.value = value
#self.message = "You entered: " repr(self.value) ".\nPlease enter a previously defined variable, number or purely numeric (and non-decimal) string."
def __str__(self):
#return self.message
print "\nYou entered: ", repr(self.value), ".\nPlease enter a previously defined variable, number or purely numeric (and non-decimal) string."

try:
print int(thing)
except NameError as inst:
temp = str.split(list(inst.args)[0])
param = str(temp[1])
param = param.replace("'","")
raise MyError(param)
pass
except (TypeError,ValueError,SyntaxError):
stuff = repr(thing)
raise MyError(stuff)
pass

And this is the output in the interpreter (if it's relevant, I am using the python interpreter in Emacs):

>>>
You entered: 'thing'
Please enter a previously defined variable, number or purely numeric (and non-decimal) string.

You entered: 'thing'
Please enter a previously defined variable, number or purely numeric (and non-decimal) string.
Traceback (most recent call last):
File "/tmp/py14824uqc", line 9, in <module>
raise MyError(param)
MyError: <unprintable MyError object>

I don't know why it's printing the message twice either, but to be honest I can live with that.

Thanks for any help!
 
Last edited:
Physics news on Phys.org
Never mind - got it working. It was just completely wrong.