提高尝试和断言之间的区别 [英] Difference between Raise Try and Assert

查看:153
本文介绍了提高尝试和断言之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习Python已有一段时间了,raise函数和assert确实很相似(我意识到是它们都使应用程序崩溃,与try不同-除外)确实很相似,我看不到任何情况在try上使用raiseassert的位置.

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.

那么,提升",尝试"和断言"之间有什么区别?

So, what is the difference between Raise, Try and 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块一起使用.引发您选择的错误,可以按如下所示进行自定义,并且如果您passcontiune脚本,则不会停止脚本;或可以是预定义的错误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 contiune 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 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 how ever you like. No example since there's one above.

这篇关于提高尝试和断言之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆