开发者

User defined Exception doubt

开发者 https://www.devze.com 2023-01-31 23:15 出处:网络
I have this exception class class Value(Exception): def __init__(self,val): self.val = val def __str__(self):

I have this exception class

class Value(Exception):
    def __init__(self,val):
        self.val = val

    def __str__(self):
        return repr(self.val)

raise Value('4')

and the exception comes as

Traceback (most recent call last):
File "<module1>", line 20, in <module>
Value: '4'

------------------------------------upd开发者_StackOverflow中文版ate------

I found out a typo mistake thanks to mark.... but my problem now is that say I want to display 4 and a string hello along with the error how to do so......

Thanks a lot


I think you meant to write val instead of value here:

def __str__(self):
    return repr(self.val) # <--- not self.value

To display multiple values I'd recommend str.format (requires Python 2.6 or newer). Example:

def __str__(self):
    return "Hello: {0}".format(self.val)

Another example:

def __str__(self):
    return "val1 = {}, val2 = {}".format(self.val1, self.val2)


>>> class Value(Exception):
 def __init__(self, val):
  self.val = val
 def __repr__(self):
  return ' ,'.join(str(x) for x in self.val) + ' hello world!'
 def __str__(self):
  return repr(self)

of course you can do whatever you want in init.. as using the syntax *val (instead of val in init) to use the class Value as you showed in your example and then simply call

Value(4, 2) or Value(4) etc...

edit:

just return self.msg in repr...

def __repr__(self):
    return self.val + self.msg #or whatever you want

my previous example showed how to accept and print multiple values...if you want just a value and a msg, and display them, you can do this:

class Value(Exception):
    def __init__(self, val, msg):
        self.val = val
        self.msg = msg
    def __repr__(self):
        return 'Error code: %s  Error message: %s' % (self.val, self.msg)
    def __str__(self):
        return repr(self)


my problem now is that say I want to display 4 and a string hello along with the error how to do so......

You should put your code inside a try/except code to handle an Exception. Here is an example:

try:
    if something:
       raise Value('4')
    # do something else here
except Value as valueException:
    print "Hello, it raises an Value exception '%s'" % valueException.message

0

精彩评论

暂无评论...
验证码 换一张
取 消