为什么"except:"能够捕获此错误但不能"除了Exception,e:"?

Spa*_*ide 2 python fabric

我有以下文件:

from fabric.api import env, execute, run

env.hosts = ['1.2.3.4']

def taskA():
    run('ls')

def main():
  try:
    execute(taskA)
  except:
    print "Exception Caught"

main()
Run Code Online (Sandbox Code Playgroud)

我运行时可以看到"Exception Caught"打印出来:

$ python test.py
[1.2.3.4] Executing task 'taskA'
[1.2.3.4] run: ls

Fatal error: Timed out trying to connect to 1.2.3.4 (tried 1 time)

Underlying exception:
    timed out

Aborting.
Exception Caught
Run Code Online (Sandbox Code Playgroud)

但是,当我将其切换为:

def main():
  try:
    execute(taskA)
  except Exception, e:
    print "Exception Caught", e

main()
Run Code Online (Sandbox Code Playgroud)

我没有看到异常被捕获:

[1.2.3.4] run: ls

Fatal error: Timed out trying to connect to 1.2.3.4 (tried 1 time)

Underlying exception:
    timed out

Aborting.
Run Code Online (Sandbox Code Playgroud)

我有能力在上面的代码中捕获错误而不是下面的错误吗?

use*_*ica 6

此异常不是源自Exception.它看起来像一个SystemExit,BaseException直接来自.except Exception只捕捉到的实例Exception.

如果你真的想要捕获绝对所有异常,你可以这样做

except BaseException as e:
Run Code Online (Sandbox Code Playgroud)

SystemExitsys.exit一些类似的函数抛出,导致解释器关闭(或至少结束线程),同时仍然运行__exit__方法和finally块.它也可以手动抛出.

BaseException因此存在,SystemExit并且一些类似的异常不会被except Exception通常不打算处理它们的块捕获.它与Java类似Throwable.就个人而言,我希望普通的except:街区没有捕获BaseException; 它打败BaseException了首先拥有的一些目的.


The*_*CAL 5

使用时except Exception, e

没有捕获BaseException或系统退出的异常 SystemExitKeyboardInterrupt并且GeneratorExit

其中,as except捕获所有异常类型。见除了区别:以及除例外为e:Python中

结果,您在使用时会看到“捕获到异常” except,而在使用时则看不到except Exception, e

来自工厂文档

如果抛出Python异常,则fab将退出,退出状态为1。