我有以下文件:爲什麼「除了:」能夠捕捉到這個錯誤而不是「除了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.
是否有原因能夠在上面的代碼中捕獲錯誤,而不是在下面?
我沒有看到回溯,所以異常*被捕獲。你確定你打印正確嗎?另外,使用'except作爲e:'。 –
@MartijnPieters:沒有回溯可能意味着它是一個SystemExit。 – user2357112
@ user2357112好點! –