断言:
当您要根据特定条件“停止”脚本并返回某些内容以加快调试速度时使用:
list_ = ["a","b","x"]assert "x" in list_, "x is not in the list"print("passed") #>> prints passedlist_ = ["a","b","c"]assert "x" in list_, "x is not in the list"print("passed")#>> Traceback (most recent call last): File "python", line 2, in <module>AssertionError: x is not in the list提高:
这很有用的两个原因:
1
/与try和except块一起使用。引发您选择的错误,可以像下面这样自定义,并且如果您
pass或
contiune脚本不停止脚本;或者可以是预定义的错误
raisevalueError()
class Custom_error(baseException): passtry: print("hello") raise Custom_error print("world")except Custom_error: print("found it not stopping now")print("im outside")>> hello>> found it not stopping now>> im outside注意到它没有停止吗?我们可以使用except块中的exit(1)停止它。
2 / Raise也可以用于重新引发当前错误,以将其传递给堆栈,以查看是否有其他方法可以处理它。
except SomeError, e: if not can_handle(e): raise someone_take_care_of_it(e)
试/除块:
完全按照您的想法进行尝试,尝试某些操作,如果出现错误,您可以按照自己的意愿进行处理。由于上面有一个,所以没有例子。



