64、手动抛出异常raise
用raise语句来引发一个异常。
在try语句中,捕捉到了异常,但是又想重新引发它(传递异常),可以使用不带参数的raise语句即可:
try: for i in range(4): if(i<100): raise ValueError("数字小于100") print(j) except Exception as e: raise
也可以携带参数,但效果是一样的
try: for i in range(4): if(i<100): raise ValueError("数字小于100") print(j) except Exception as e: raise e
如果不是在try语句中使用raise,异常对象必须有一个名字,且它们应是Error或Exception类的子类。异常后面可接异常时显示的提示信息。
if(i<100): raise ValueError("数字小于100")