引发,尝试和声明之间有什么区别? [英] What's the difference between raise, try, and assert?

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

问题描述

我学习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?

推荐答案

声明:

在您要停止"时使用根据特定条件编写脚本并返回一些内容以帮助更快地进行调试:

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.

这篇关于引发,尝试和声明之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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