raise、try 和 assert 之间有什么区别? [英] What's the difference between raise, try, and assert?
问题描述
我已经学习 Python 一段时间了,raise
函数和 assert
是(我意识到它们都会使应用程序崩溃,不像 try - 除了)非常相似,我看不到您会在 try
上使用 raise
或 assert
的情况.
I have been learning Python for a while and the raise
function and assert
are (what I realised is that both of them crash the app, unlike try - except) really similar and I can't see a situation where you would use raise
or assert
over try
.
那么,raise
、try
和 assert
有什么区别?
So, what is the difference between raise
, try
, and assert
?
推荐答案
Assert:
当你想停止"时使用基于特定条件的脚本并返回一些东西以帮助更快地调试:
Used when you want to "stop" the script based on a certain condition and return something to help debug faster:
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
提高:
Raise:
这很有用的两个原因:
1/与 try 和 except 块一起使用.引发您选择的错误,可以像下面这样自定义,如果您pass
或continue
脚本,则不会停止脚本;或者可以是预定义的错误 raise ValueError()
1/ To be used with try and except blocks. Raise an error of your choosing, could be custom like below and doesn't stop the script if you pass
or continue
the script; or can be predefined errors 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) 来停止它.
Noticed it didn't stop? We can stop it using just exit(1) in the except block.
2/Raise 也可用于重新引发当前错误,将其向上传递到堆栈,看看是否有其他东西可以处理它.
2/ Raise can also be used to re-raise the current error to pass it up the stack to see if something else can handle it.
except SomeError, e:
if not can_handle(e):
raise
someone_take_care_of_it(e)
尝试/排除块:
Try/Except blocks:
完全按照你的想法去做,如果出现错误,你会尝试一些事情,你可以抓住它并按照你喜欢的方式处理它.没有例子,因为上面有一个.
Does exactly what you think, tries something if an error comes up you catch it and deal with it however you like. No example since there's one above.
这篇关于raise、try 和 assert 之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!