我们何时需要使用“尝试,除了“在python中?它是否类似于"if,else"? [英] When do we need to use " try, except" in python? Is it similar to "if, else"?

查看:51
本文介绍了我们何时需要使用“尝试,除了“在python中?它是否类似于"if,else"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

try: 
  print(x)
except:
  print("Done!!")

为什么需要使用 try except .

Why do we need to use, try and except.

有人可以解释 try except 方法吗?您能举例说明一下吗?

Can someone explain try and except method? Could you answer with an example and explanation.

推荐答案

try except 块用于捕获和处理异常.该程序将首先正常"运行 try 语句.如果在try语句中触发了任何异常,则将触发except语句.例如,

The try and except blocks are used to catch and handle exceptions. The program will first run the try statement "normally". If there are any exceptions that trigger in the try statement, the except statement will trigger. For example,

try:
    print(str) #Here, str isn't defined and you will get an exception which triggers the except statement
except NameError: #Here, you specify which exception you think might happen
    #Do something

您可以根据需要设置任意数量的异常块!另外请注意,如果捕获到异常,则其他不会触发.另外请注意,没有参数的异常块将捕获所有异常.

You can have as many exception blocks as you want! Also note that if you catch an exception the other ones will not trigger. Also note that an exception block with no arguments will catch all exceptions.

即使没有异常,也可以添加并触发finally块.这对于关闭和清洁物体很有帮助.另一个例子,

The finally block can be added on and triggers even if there was an exception or not. This can be helpful for closing and cleaning objects. Another example,

try:
    #stuff
except:
    #stuff if exception
finally:
    #do stuff even if there is or is not an exception

我还应该提到 pass 函数.如果要忽略异常,则应使用它.例子,

I should also mention the pass function. You should use it if you want to ignore exceptions. Example,

try:
    #stuff
except:
    pass #i don't want to do anything

希望我能帮上忙!

这篇关于我们何时需要使用“尝试,除了“在python中?它是否类似于"if,else"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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