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



我有以下文件:

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

当我运行这个时,我能够看到打印的"异常捕获":

$ 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

但是,当我将其切换到此时:

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

我没有看到异常被捕获:

[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派生的。它看起来像一个SystemExit,直接来源于BaseExceptionexcept Exception只捕获Exception的实例。

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

except BaseException as e:

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

BaseException存在,因此SystemExit和一些类似的异常不会被通常不打算处理它们的except Exception块捕获。它类似于Java的Throwable。就个人而言,我希望普通except:块不会抓住BaseException;它首先违背了BaseException的一些目的。

当你使用except Exception, e时,它

未捕获BaseException或系统退出异常SystemExitKeyboardInterruptGeneratorExit

其中 asexcept捕获所有异常类型。请参阅 Python 中的 except: 和 except Exception as e: 之间的区别。

因此,您在使用except时会看到"异常捕获",但在使用except Exception, e时不会

来自晶圆厂文档

如果引发 Python 异常,fab 将中止,退出状态为 1。

相关内容

最新更新