About catching ANY exception

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

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

8条回答
  •  不要未来只要你来
    2020-11-22 08:04

    Very simple example, similar to the one found here:

    http://docs.python.org/tutorial/errors.html#defining-clean-up-actions

    If you're attempting to catch ALL exceptions, then put all your code within the "try:" statement, in place of 'print "Performing an action which may throw an exception."'.

    try:
        print "Performing an action which may throw an exception."
    except Exception, error:
        print "An exception was thrown!"
        print str(error)
    else:
        print "Everything looks great!"
    finally:
        print "Finally is called directly after executing the try statement whether an exception is thrown or not."
    

    In the above example, you'd see output in this order:

    1) Performing an action which may throw an exception.

    2) Finally is called directly after executing the try statement whether an exception is thrown or not.

    3) "An exception was thrown!" or "Everything looks great!" depending on whether an exception was thrown.

    Hope this helps!

提交回复
热议问题