User Defined Exception Exception

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 is

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

------------------------------------ update ------

I found a typography error due to the sign .... but now my problem is that I want to display 4 and the welcome line along with the error how to do it ......

Thank you so much

+3
source share
3 answers

I think you wanted to write valinstead valuehere:

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

To display multiple values, I would recommend str.format(requires Python 2.6 or later). Example:

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

Another example:

def __str__(self):
    return "val1 = {}, val2 = {}".format(self.val1, self.val2)
+2
source
>>> 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)

, , , init.., * val ( val init), Value, ,

(4, 2) (4) ..

:

self.msg ...

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

, ... msg , :

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)
0

Now my problem is that I want to display 4 and the welcome line along with the error how to do it ......

You must put your code inside the try / except code to handle the 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
source

Source: https://habr.com/ru/post/1781231/


All Articles