在 Python 中,except: 和 except Exception as e: 之间的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18982610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between except: and except Exception as e: in Python
提问by narendranathjoshi
Both the following snippets of code do the same thing. They catch every exception and execute the code in the except:
block
以下两个代码片段都做同样的事情。他们捕获每个异常并执行except:
块中的代码
Snippet 1 -
片段 1 -
try:
#some code that may throw an exception
except:
#exception handling code
Snippet 2 -
片段 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?
两种结构的确切区别是什么?
采纳答案by agf
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
:
但它不会捕获BaseException
或系统退出异常SystemExit
,KeyboardInterrupt
并且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 Exceptionssection of the docs and the Errors and Exceptionssection of the tutorial for more info.
回答by Veedrac
except:
accepts allexceptions, whereas
接受所有异常,而
except Exception as e:
only accepts exceptions that you're meantto catch.
只接受例外,你的意思来抓。
Here's an example of one that you're not meant to catch:
下面是一个你不想抓住的例子:
>>> try:
... input()
... except:
... pass
...
>>> try:
... input()
... except Exception as e:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
The first one silenced the KeyboardInterrupt
!
第一个沉默了KeyboardInterrupt
!
Here's a quick list:
这是一个快速列表:
issubclass(BaseException, BaseException)
#>>> True
issubclass(BaseException, Exception)
#>>> False
issubclass(KeyboardInterrupt, BaseException)
#>>> True
issubclass(KeyboardInterrupt, Exception)
#>>> False
issubclass(SystemExit, BaseException)
#>>> True
issubclass(SystemExit, Exception)
#>>> False
If you want to catch any of those, it's best to do
如果你想抓住其中任何一个,最好这样做
except BaseException:
to point out that you know what you're doing.
指出你知道你在做什么。
Allexceptions stem from BaseException
, and those you're meant to catch day-to-day (those that'll be thrown forthe programmer) inherit too from Exception
.
所有异常都源自BaseException
,而那些您打算每天捕获的异常(将为程序员抛出的异常)也继承自Exception
.
回答by Diego Herranz
There are differences with some exceptions, e.g. KeyboardInterrupt.
除了一些例外,例如KeyboardInterrupt 之外,还有一些区别。
Reading PEP8:
阅读PEP8:
A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).
一个空的 except: 子句将捕获 SystemExit 和 KeyboardInterrupt 异常,使得用 Control-C 中断程序变得更加困难,并且可以掩盖其他问题。如果要捕获所有表示程序错误的异常,请使用except Exception:(bare except 等价于except BaseException:)。
回答by Silas Ray
Using the second form gives you a variable (named based upon the as
clause, in your example e
) in the except
block scope with the exception object bound to it so you can use the infomration in the exception (type, message, stack trace, etc) to handle the exception in a more specially tailored manor.
使用第二种形式在块范围内为您提供一个变量(as
在您的示例中基于子句命名e
),except
异常对象绑定到它,因此您可以使用异常中的信息(类型、消息、堆栈跟踪等)来在更特别定制的庄园中处理异常。
回答by jouell
Another way to look at this. Check out of the details of the exception:
看待这个问题的另一种方式。查看异常的详细信息:
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']
There are lots of "things" to access using the 'as e' syntax.
使用“as e”语法可以访问很多“事物”。
This code was solely meant to show the details of this instance.
此代码仅用于显示此实例的详细信息。