except: 和 except Exception as e 之间的区别:

新手上路,请多包涵

以下两段代码都做同样的事情。他们捕获每个异常并执行 except: 块中的代码

片段 1 -

 try:
    #some code that may throw an exception
except:
    #exception handling code

片段 2 -

 try:
    #some code that may throw an exception
except Exception as e:
    #exception handling code

这两种结构到底有什么区别?

原文由 narendranathjoshi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

在第二个中,您可以访问异常对象的属性:

 >>> def catch():
...     try:
...         asd()
...     except Exception as e:
...         print e.message, e.args
...
>>> catch()
global name 'asd' is not defined ("global name 'asd' is not defined",)

但是它不会捕获 BaseException GeneratorExit KeyboardInterrupt 验证异常 SystemExit

 >>> def catch():
...     try:
...         raise BaseException()
...     except Exception as e:
...         print e.message, e.args
...
>>> catch()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in catch
BaseException

一个简单的除外:

 >>> def catch():
...     try:
...         raise BaseException()
...     except:
...         pass
...
>>> catch()
>>>

有关详细信息,请参阅文档的 内置异常 部分和教程的 错误和异常 部分。

原文由 agf 发布,翻译遵循 CC BY-SA 3.0 许可协议

except:

接受 所有 异常,而

except Exception as e:

只接受您 捕获的异常。

下面是一个你不想捕捉的例子:

 >>> try:
...     input()
... except:
...     pass
...
>>> try:
...     input()
... except Exception as e:
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyboardInterrupt

第一个使 KeyboardInterrupt 沉默了!

这是一个快速列表:

 issubclass(BaseException, BaseException)
#>>> True
issubclass(BaseException, Exception)
#>>> False

issubclass(KeyboardInterrupt, BaseException)
#>>> True
issubclass(KeyboardInterrupt, Exception)
#>>> False

issubclass(SystemExit, BaseException)
#>>> True
issubclass(SystemExit, Exception)
#>>> False

如果你想抓住其中任何一个,最好做

except BaseException:

指出你知道自己在做什么。


所有 异常都源于 BaseException ,而那些你打算每天捕捉的异常(那些将抛给程序员 异常)也继承自 Exception

原文由 Veedrac 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题