代码之家  ›  专栏  ›  技术社区  ›  Carla

Python无法访问系统。在try区段内退出

  •  0
  • Carla  · 技术社区  · 4 年前

    try 第节:

    try:
        quote = getValue(i)
        writeData(i,quote)
    except:
        print("Oops!", sys.exc_info()[0], "occurred.")
    

    getValue(value)

    sys.exit()
    

    但是, except 子句还截获此类错误:

    Oops! <class 'SystemExit'> occurred.
    

    从我的Java背景来看 System.exit() 强制终止程序。Python中强制退出程序的最简单方法是什么,即使是使用 除了 条款

    4 回复  |  直到 4 年前
        1
  •  2
  •   chepner    4 年前

    sys.exit 只是提出了一个问题 SystemExit 异常,它是 BaseException 但不是 Exception

    >>> issubclass(SystemExit, Exception)
    False
    >>> issubclass(SystemExit, BaseException)
    True
    >>> issubclass(Exception, BaseException)
    True
    

    基地 except 全部的 except BaseException ,这就是为什么您几乎不想使用裸机 使用 except Exception 只捕获异常之类的错误,而不捕获流控制异常。

    try:
        quote = getValue(i)
        writeData(i,quote)
    except Exception:
        print("Oops!", sys.exc_info()[0], "occurred.")
    

    除了 尽可能多地使用条款。当你做像这样广泛的事情时 例外情况除外 ,您通常希望退出程序或重新引发异常,而不是仅通过日志记录将其视为已处理。

        2
  •  1
  •   Cereaubra    4 年前

    你可以赶上火车 SystemException sys.exit() 再一次:

    import sys
    
    try:
        sys.exit(1)
    except SystemExit as e:
        sys.exit(e.code)
    
        3
  •  0
  •   md2perpe    4 年前

    这个 sys.exit() 电话 nothing more 然后提出了一个 SystemExit

    您可以专门处理该异常并重新确认它:

    try:
        quote = getValue(i)
        writeData(i,quote)
    except SystemExit:
        raise
    except:
        print("Oops!", sys.exc_info()[0], "occurred.")