【问题标题】:How to see the error and still keep the program on in the Python shell?如何查看错误并仍然在 Python shell 中保持程序运行?
【发布时间】:2010-10-16 19:52:34
【问题描述】:

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

【问题讨论】:

    标签: python exception exception-handling error-handling


    【解决方案1】:

    在 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
    

    【讨论】:

      【解决方案2】:
      import traceback
      
      try:
          # do whatever you want
      except Exception:
          traceback.print_exc()
      

      当然,您应该在实际场景中更加具体,即您不应该捕获并忽略所有 Exception 实例,只捕获和忽略您感兴趣并且您知道它们可以安全忽略的实例。

      还要注意,如果在try..except 块中的某个地方发生异常,则执行将在try..except 块之后继续,而不是在下一条语句处。这可能是最接近您想要实现的目标。

      【讨论】:

      • 谢谢!这真的很有帮助!
      猜你喜欢
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      相关资源
      最近更新 更多