Difference between except: and except Exception as e:(except: 和 except Exception as e 之间的区别:)
问题描述
Both the following snippets of code do the same thing. They catch every exception and execute the code in the except:
block
Snippet 1 -
try:
#some code that may throw an exception
except:
#exception handling code
Snippet 2 -
try:
#some code that may throw an exception
except Exception as e:
#exception handling code
What is exactly the difference in both the constructs?
In the second you can access the attributes of the exception object:
>>> 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",)
But it doesn't catch BaseException
or the system-exiting exceptions SystemExit
, KeyboardInterrupt
and GeneratorExit
:
>>> 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
Which a bare except does:
>>> def catch():
... try:
... raise BaseException()
... except:
... pass
...
>>> catch()
>>>
See the Built-in Exceptions section of the docs and the Errors and Exceptions section of the tutorial for more info.
这篇关于except: 和 except Exception as e 之间的区别:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:except: 和 except Exception as e 之间的区别:
基础教程推荐
- 症状类型错误:无法确定关系的真值 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01