除了以外的區別:和除了Ex:e:在Python中 - Difference between except: and except Exception as e: in Python -开发者知识库

除了以外的區別:和除了Ex:e:在Python中 - Difference between except: and except Exception as e: in Python -开发者知识库,第1张

Both the following snippets of code do the same thing. They catch every exception and execute the code in the except: block

以下兩段代碼都做同樣的事情。它們捕獲每個異常並執行except:block中的代碼

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?

這兩種結構究竟有什么不同?

5 个解决方案

#1


80  

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 Exceptions section of the docs and the Errors and Exceptions section of the tutorial for more info.

有關詳細信息,請參閱本教程的“內置異常”部分和本教程的“錯誤和異常”部分。

最佳答案:

本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复