断言:
当您想根据特定条件“停止”脚本并返回一些内容以帮助更快地调试时使用:
list_ = ["a","b","x"]
assert "x" in list_, "x is not in the list"
print("passed")
#>> prints passed
list_ = ["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 或 continue 脚本,则不会停止脚本;或者可以是预定义的错误raise ValueError()
class Custom_error(BaseException):
pass
try:
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)
尝试/排除块:
完全按照你的想法去做,如果出现错误,你会尝试一些事情,然后你会发现它并按照你喜欢的方式处理它。没有例子,因为上面有一个。