python - 如何看到错误并仍然在 Python shell 中保持程序运行?

标签 python exception error-handling

我知道 try/except 可以处理我程序中的错误。 但是,有没有办法让程序执行时显示错误,忽略并继续执行呢?

最佳答案

在 VBScript 和其他 VB 派生语言中,您可以使用“ON ERROR GOTO NEXT”获得这种行为。

Python 中不存在这样的行为。即使你像这样包装每个顶级语句:

try:
  do_something()
except Exception as e:
  print e

try:
  do_something_else()
except Exception as e:
  print e

在抛出异常时,您仍然会得到 do_something 中的语句被跳过的结果。

不过,如果您有特定的用例,可能还有其他可以接受的答案。例如,在顶层循环中:

while True:
  cmd = get_command()
  if cmd == 'quit': break
  try:
    run_command(cmd)
  except Exception as e:
    print "Error running " + cmd + ":"
    print e

关于python - 如何看到错误并仍然在 Python shell 中保持程序运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3950505/

相关文章:

python - 想要乘法,而不是重复变量

javascript - 如何使用动态表中的唯一 ID 通过按钮传递数据

java - 如何在Java中的方法 "throws"上指定消息?

c++ - 删除 using namespace std 会导致程序得到错误的结果

php - 如何从 fatal error "Allowed memory size exhausted"中恢复

c# - WebView和错误管理,怎么了?

python - SQLAlchemy:如何通过事件监听器有条件地添加到集合?

python - 导入 someModule,而不是 clr.AddReferenceToFile ("someModule")?

javascript - 如何在 Promise 中捕获未捕获的异常

java |如果父线程终止则终止所有子线程