python - 在一个try语句中不能同时使用except和finally子句?
PHP中文网
PHP中文网 2017-04-17 11:35:14
0
3
1994
try:
    1/0
except:
    print 'something wrong happened..'
finally:
    print 'it seems i cannot be with except'

除非是我对《python基础教程》上面这句话理解有问题,这段代码运行完全没有问题,求解惑。

PHP中文网
PHP中文网

认证0级讲师

reply all(3)
阿神

The answer can definitely be used together

Let’s look at the use of else first:

try:
    ...
exception:
    ...
else:
    ...

Only when no exception occurs in try and all codes are completely successful will it transfer to else

Look at finally:

Finally is a sentence that will be executed regardless of whether the exception is caught or not. Finally can be used alone with try, or with except, including else

try: A
except MyException: B
else: C
finally: D

The execution order may be A-B-D or A-C-D When finally is used alone with try, 不是用来捕捉异常,常常是用来维持一致的行为。

When an exception occurs in the try scope, it will immediately jump to finally. After finally is executed, 会继续向上一层引发异常

  • One reason for writing this way is that if an exception occurs within the finally block, you can create an exception handler at the same (outer) level as the existing exception handler to handle it. This essentially allows you to handle errors that occur in both the original try block and the finally block at the same time. The only problem with this approach is that when an exception does occur in the finally block, you lose the original exception. Contextual information, unless you saved it somewhere.
  • One reason against this way of writing is: in many cases, the exception handler needs to do some cleaning up work, and if you use a finally statement block to release certain resources before exception handling, , you can no longer do this work. Simply put, the finally statement block is not as "final" as you think.

  • A final note: if the code in finally raises another exception or terminates due to return, break, or continue syntax, the original exception will be lost and cannot be re-raised.

Reference: python core programming

阿神

The python version corresponding to this book is too old. It cannot be used together with py2.4 before, but 2.5+ will do.

This kind of old and not updated book is the same as "pE INTO PYTHON". Don't read it if you can. I recommend "a byte of python" for beginners.

Peter_Zhu

A simple understanding is that no matter whether an exception occurs in the statement in try, the content in finaly will be executed in the end.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template