【问题标题】:Why is "except:" able to catch this error but not "except Exception, e:"?为什么“except:”能够捕捉到这个错误,但不能捕捉到“except Exception, e:”?
【发布时间】:2017-07-31 19:58:32
【问题描述】:

我有以下文件:

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 Exception as e:
  • @MartijnPieters:没有回溯可能意味着它是 SystemExit。
  • @user2357112 好点!

标签: python fabric


【解决方案1】:

此异常并非源自Exception。它看起来像一个SystemExit,它直接派生自BaseExceptionexcept Exception 仅捕获 Exception 的实例。

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

except BaseException as e:

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

BaseException 存在,所以SystemExit 和一些类似的异常不会被通常不打算处理它们的except Exception 块捕获。它类似于 Java 的Throwable。就个人而言,我希望普通的except: 块没有捕获BaseException;它首先破坏了拥有BaseException 的一些目的。

【讨论】:

    【解决方案2】:

    当你使用except Exception, e时,它

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

    except 捕获所有异常类型。见Difference between except: and except Exception as e: in Python

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

    来自工厂docs

    如果抛出 Python 异常,fab 会以退出状态 1 中止。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 2016-04-06
      • 2021-07-25
      相关资源
      最近更新 更多