除了以外的区别:和除了Ex:e:在Python中

时间:2013-09-24 13:11:42

标签: python python-3.x

以下代码片段都做同样的事情。它们捕获每个异常并执行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

两种构造的区别是什么?

6 个答案:

答案 0 :(得分:106)

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

>>> 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或系统退出异常SystemExitKeyboardInterruptGeneratorExit

>>> 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()
>>> 

有关详细信息,请参阅文档的Built-in Exceptions部分和教程的Errors and Exceptions部分。

答案 1 :(得分:36)

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,以及您日常想要抓住的那些( > em>程序员也从Exception继承。

答案 2 :(得分:9)

某些例外情况存在差异,例如:一个KeyboardInterrupt。

阅读PEP8

  

一个裸的except:子句将捕获SystemExit和KeyboardInterrupt   异常,使用Control-C更难中断程序,   并且可以掩饰其他问题。如果你想捕获所有异常   那个信号程序错误,使用除了Exception :(除了是   相当于除了BaseException:)。

答案 3 :(得分:2)

使用第二个表单为as块作用域中的变量(基于e子句,在except示例中命名),并绑定了异常对象,因此您可以使用异常中的信息(类型,消息,堆栈跟踪等)来在更专门定制的庄园中处理异常。

答案 4 :(得分:1)

另一种查看方式。查看异常的详细信息:

In [49]: try: 
    ...:     open('file.DNE.txt') 
    ...: except Exception as  e: 
    ...:     print(dir(e)) 
    ...:                                                                                                                                    
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'with_traceback']

使用“ as e”语法可以访问许多“事物”。

此代码仅用于显示该实例的详细信息。

答案 5 :(得分:-5)

异常意味着错误。 在运行时查找错误。处理运行时错误称为异常处理。 它有两个街区 尝试 除了 尝试: 它只是一个块。它只是例外。 除了: 这是一个街区。 它需要异常并处理异常。 并执行。