天天看点

Python3面向对象--3.异常(2)抛出异常

raise <异常对象>就可以抛出异常了。

抛出异常后,异常对象后的代码便不会被执行。

class EvenOnly(list):
    "只允许输入偶数"
    def append(self, integer):
        if not isinstance(integer.int):
            raise TypeError("only integers can be added")
        if not integer % 2:
            raise ValueError("Only even numbers can be added")
        super().append(integer)

e=EvenOnly()
e.append("小明")
e.append(3)
e.append(2)

Traceback (most recent call last):
  File "D:/untitled1/Book/venv/Include/f.py", line 10, in <module>
    e.append("小明")
  File "D:/untitled1/Book/venv/Include/f.py", line 3, in append
    if not isinstance(integer.int):
AttributeError: 'str' object has no attribute 'int'