Python中except:和except Exception之间的区别,例如e:

发布于 2021-01-29 15:00:04

以下两个代码段都执行相同的操作。他们捕获每个异常并执行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

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

关注者
0
被浏览
204
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

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

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看