问题:Python中except:和except Exception之间的区别,例如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

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

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?


回答 0

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

>>> 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或系统退出异常SystemExitKeyboardInterrupt并且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

除了一个裸露的:

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

有关更多信息,请参阅文档的“ 内置异常”部分和本教程的“ 错误与异常”部分。

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.


回答 1

except:

接受所有exceptions,而

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

except:

accepts all exceptions, whereas

except Exception as e:

only accepts exceptions that you’re meant to 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!

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.


All exceptions stem from BaseException, and those you’re meant to catch day-to-day (those that’ll be thrown for the programmer) inherit too from Exception.


回答 2

除某些exceptions外,还有其他区别,例如KeyboardInterrupt。

阅读PEP8

仅有的except:子句将捕获SystemExit和KeyboardInterrupt异常,这使得使用Control-C中断程序更加困难,并且可以掩盖其他问题。如果要捕获所有表示程序错误的异常,请使用Exception:除外(裸除等效于BaseException:除外)。

There are differences with some exceptions, e.g. KeyboardInterrupt.

Reading 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:).


回答 3

使用第二种形式会在块范围内为您提供一个变量(根据as示例中的子句命名e),并except绑定了异常对象,因此您可以在异常中使用信息(类型,消息,堆栈跟踪等)来在更特别的庄园中处理exceptions情况。

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.


回答 4

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

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”语法可以访问许多“事物”。

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

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.

This code was solely meant to show the details of this instance.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。