search

Home  >  Q&A  >  body text

python - 在一个try语句中不能同时使用except和finally子句?

try:
    1/0
except:
    print 'something wrong happened..'
finally:
    print 'it seems i cannot be with except'

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

PHP中文网PHP中文网2805 days ago2000

reply all(3)I'll reply

  • 阿神

    阿神2017-04-17 11:37:14

    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

    reply
    0
  • 阿神

    阿神2017-04-17 11:37:14

    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.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 11:37:14

    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.

    reply
    0
  • Cancelreply