Catch any error in Python

前端 未结 8 1663
一个人的身影
一个人的身影 2021-02-01 14:24

Is it possible to catch any error in Python? I don\'t care what the specific exceptions will be, because all of them will have the same fallback.

8条回答
  •  遥遥无期
    2021-02-01 14:59

    Quoting the bounty text:

    I want to be able to capture ANY exception even weird ones like keyboard interrupt or even system exit (e.g. if my HPC manger throws an error) and get a handle to the exception object e, whatever it might be. I want to process e and custom print it or even send it by email

    Look at the exception hierarchy, you need to catch BaseException:

    BaseException
     +-- SystemExit
     +-- KeyboardInterrupt
     +-- GeneratorExit
     +-- Exception
    

    This will capture KeyboardInterrupt, SystemExit, and GeneratorExit, which all inherit from BaseException but not from Exception, e.g.

    try:
        raise SystemExit
    except BaseException as e:
        print(e.with_traceback)
    

提交回复
热议问题