我有以下文件:
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()
当我运行时,我能够看到“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
然而,当我把它切换到这个时:
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.
我有能力在上面的代码中捕获错误而不是下面的错误吗?
答案 0 :(得分:5)
此异常不是来自Exception
。它看起来像SystemExit
,直接来自BaseException
。 except Exception
仅捕获Exception
。
如果您真的想要捕获绝对所有异常,可以使用
执行此操作except BaseException as e:
SystemExit
和一些类似函数抛出 sys.exit
,导致解释器关闭(或者至少结束线程),同时仍然运行__exit__
方法和finally
块。它也可以手动抛出。
BaseException
存在SystemExit
,并且except Exception
块通常无意处理它们,因此没有捕获到一些类似的异常。它类似于Java的Throwable
。就个人而言,我希望普通except:
块没有捕获BaseException
;它首先取消了BaseException
的目的。
答案 1 :(得分:4)
使用except Exception, e
时,
不会捕获
BaseException
或系统退出的异常SystemExit
,KeyboardInterrupt
和GeneratorExit
其中except
捕获所有异常类型。请参阅Difference between except: and except Exception as e: in Python。
因此,您在使用except
时会看到“异常被捕获”,但在使用except Exception, e
来自fab docs
如果抛出Python异常,则fab将以退出状态1中止。