Python 简介
A try / except / finally statement, such as:
try: ...guarded clause... except ...expression...: ...exception handler code... finally: ...clean-up code...
is equivalent to the nested statement:
try: try: ...guarded clause... except ...expression...: ...exception handler code... finally: ...clean-up code...
- 为什么它相当于嵌套表单?
是否可以写成与不带
finally
的形式等价?是否相当于
try: ...guarded clause... except ...expression...: ...exception handler code... ...clean-up code... ...clean-up code...
谢谢。
最佳答案
- 因为这就是它的定义方式。因为以这种方式定义它是有用且标准的,并且因为没有其他有用的方法来定义它。
是的,但不是你这样做的方式。
try: do_stuff() except OneProblem: handle_it() except DifferentProblem: handle_that() finally: cleanup()
相当于
try: try: do_stuff() except OneProblem: handle_it() except DifferentProblem: handle_that() except: # Clean up if an unhandled exception happened, then restore the exception. cleanup() raise # Also clean up if we're not propagating an exception. cleanup()
就清理而言,总是会发生并且不会发生两次,尽管异常链接和回溯之类的行为可能会有所不同。
关于python - 相当于 try/except/finally 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46229716/