Python中的Try / Except:如何正确忽略异常? [英] Try/Except in Python: How do you properly ignore Exceptions?

查看:1522
本文介绍了Python中的Try / Except:如何正确忽略异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您只想尝试 - 除了不处理异常,您如何在Python中执行此操作?

When you just want to do a try-except without handling the exception, how do you do it in Python?

以下是正确的方法?

try:
    shutil.rmtree(path)
except:
    pass


推荐答案

try:
  doSomething()
except: 
  pass

try:
  doSomething()
except Exception: 
  pass

区别是,第一个也会抓住 KeyboardInterrupt SystemExit 和类似的东西,直接从 exception.BaseException 而不是 exceptions.Exception
请参阅文档了解详情:

The difference is, that the first one will also catch KeyboardInterrupt, SystemExit and stuff like that, which are derived directly from exceptions.BaseException, not exceptions.Exception.
See documentation for details:

  • try statement — http://docs.python.org/reference/compound_stmts.html#try
  • exceptions — http://docs.python.org/library/exceptions

这篇关于Python中的Try / Except:如何正确忽略异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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