About catching ANY exception

后端 未结 8 1222
一整个雨季
一整个雨季 2020-11-22 07:23

How can I write a try/except block that catches all exceptions?

8条回答
  •  再見小時候
    2020-11-22 07:53

    To catch all possible exceptions, catch BaseException. It's on top of the Exception hierarchy:

    Python 3: https://docs.python.org/3.5/library/exceptions.html#exception-hierarchy

    Python 2.7: https://docs.python.org/2.7/library/exceptions.html#exception-hierarchy

    try:
        something()
    except BaseException as error:
        print('An exception occurred: {}'.format(error))
    

    But as other people mentioned, you would usually not need this, only for specific cases.

提交回复
热议问题