通过创建一个新的异常类,就可以命名自己的异常,异常应该是典型的继承自Exception类
例如:
# 定义了一个自己的异常类,可在适当时候通过raise来触发它
class ExError(Exception): pass def exrror(num): if num ==100: raise ExError("the num must not be %d" %num) else: print(num) exrror(100)
“““
---------------------------------------------------------------------------
ExError Traceback (most recent call last)
<ipython-input-28-febd2db30885> in <module>()
9 print(num)
10
---> 11 exrror(100)
<ipython-input-28-febd2db30885> in exrror(num)
5 def exrror(num):
6 if num ==100:
----> 7 raise ExError("the num must not be %d" %num)
8 else:
9 print(num)
ExError: the num must not be 100
”””