except: 和except Exception as e 之间的区别: [英] Difference between except: and except Exception as e:

查看:42
本文介绍了except: 和except Exception as e 之间的区别:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个代码片段都做同样的事情.它们捕获每个异常并执行 except:

中的代码

片段 1 -

尝试:#一些可能抛出异常的代码除了:#异常处理代码

片段 2 -

尝试:#一些可能抛出异常的代码除了作为 e 的例外:#异常处理代码

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

解决方案

第二个可以访问异常对象的属性:

<预><代码>>>>定义捕捉():... 尝试:... asd()... 除了 e 的异常:... 打印 e.message, e.args...>>>抓住()全局名称 'asd' 未定义(全局名称 'asd' 未定义",)

但它不会捕获BaseException 或系统退出异常SystemExitKeyboardInterruptGeneratorExit:

<预><代码>>>>定义捕捉():... 尝试:...引发 BaseException()... 除了 e 的异常:... 打印 e.message, e.args...>>>抓住()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件<stdin>",第 3 行,在 catch 中基本异常

裸机除外:

<预><代码>>>>定义捕捉():... 尝试:...引发 BaseException()... 除了:... 经过...>>>抓住()>>>

请参阅文档的内置异常部分和错误和异常 部分教程以获取更多信息.

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 之间的区别:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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