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.
The answer can definitely be used together
Let’s look at the use of else first:
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
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,
会继续向上一层引发异常
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.
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.