User Based Exception program not working
This code does not work. Please tell what the error is....
class Error(Exception):
def __init__(self,mssg):
self.mssg = mssg
class InputError(Error):
def __init__(self,val):
super("Input Error")
print val
Now I write in other part of my program
a = raw_input("Enter a number from 0-9: "开发者_C百科)
if (ord(a)>47 and ord(a)<58):
pass
else:
raise InputError(a)
Now when I pass 'a' I get super expected a type but got a string
I just want to pass that message to the base class and display it along with the wrong value.
What am I doing wrong here
The problem is that you're using super()
incorrectly. The proper way is:
class InputError(Error):
def __init__(self, val):
super(InputError, self).__init__(val)
print val
super()
is used to access methods of a superclass that have been overridden in the subclass, not to instantiate the superclass with arguments.
What you appear to be trying to do is something like:
class InputError(Error):
def __init__(self,val):
super(InputError).__init__("Input Error")
print val
although this isn't necessarily a good idea.
super
is supposed to be called like this:
class InputError(Error):
def __init__(self,val):
super(InputError, self).__init__("Input Error")
print val
super
is a python builtin which takes the type of an object as its argument, not some (arbitrary) string, as you seem to have done. You probably mean
super(InputError, self).__init__("Input Error")
[In Python 3.x, this can just be super().__init__("Input Error")
]
Note that because of the name of your exception is already InputError
, it's not clear what the string message adds to it...
See this question and the python docs.
精彩评论