Python exception capture try except else finally has return execution order inquiry

Source: Internet
Author: User
Tags try catch

Reprinted from Https://www.cnblogs.com/JohnABC/p/4065437.html

Learning Python or other programming languages with abnormal control , it is very possible to say that the execution of try except finally (try Catch finally) is very simple, nothing but an exception to execute except, finally whether or not an exception will be executed , the general principle is this, but if it involves a more detailed and complex path, plus a return statement, it's not that simple.

1. Case without return statement

print ' This was a test of code path in try...except...else...finally ' print ' ********************************************* ' Def excepttest ():    try:        print ' doing some work, and maybe exception'll be raised '        raise Inde Xerror (' index error ')        #print ' after exception raise '        #return 0             except Keyerror, E:        print ' in Keyerror Except '        print e        #return 1    except Indexerror, E:        print ' in indexerror except '        print e        # Return 2    except Zerodivisionerror, E:        print ' in Zerodivisionerror '        print e        #return 3    Else:        print ' no exception '        #return 4    finally:        print ' in finally '        #return 5 ResultCode = Excepttest ( ) Print ResultCode
The code above is the code that is used all the time, but the code that is temporarily unused is comment.

An exception occurs, and the exception is caught, and finally is processed at the end, the output of the above code:

This was a test of code path in try...except...else...finally********************************************************** **doing some work, and maybe exception'll be Raisedin indexerror exceptindex Errorin finallynone

Then we gradually add the return statement to each case of the code above to see how the code executes after the return statement is added.

2. The case of adding a return statement

print ' This was a test of code path in try...except...else...finally ' print ' ********************************************* ' Def excepttest ():    try:        print ' doing some work, and maybe exception'll be raised '        raise Inde Xerror (' index error ')        print ' After exception raise '        return 0             except Keyerror, E:        print ' in Keyerror Except '        print e        return 1    except Indexerror, E:        print ' in indexerror except '        print e        return 2    except Zerodivisionerror, E:        print ' in Zerodivisionerror '        print e        return 3    else:        print ' no exception '        return 4    finally:        print ' in finally '        return 5 ResultCode = Excepttest () print ResultCode

At this point all branches have a return statement, and an exception is thrown to look at the output:

This was a test of code path in try...except...else...finally********************************************************** **doing some work, and maybe exception'll be Raisedin indexerror exceptindex Errorin finally5

After the exception occurs, the raise statement is no longer executed, and then to the catch exception statement, but the catch exception module has a return, is not this time to continue to perform a direct return? However, this is in conflict with the finally statement's inevitable execution, and you can see in the results that finally it executes and the return value is 5, the return value at the finally de.

Then, let's take a look at the return value of finally to comment out, and see what the return value is?

The code is as follows:

print ' This was a test of code path in try...except...else...finally ' print ' ********************************************* ' Def excepttest ():    try:        print ' doing some work, and maybe exception'll be raised '        raise Inde Xerror (' index error ')        print ' After exception raise '        return 0             except Keyerror, E:        print ' in Keyerror Except '        print e        return 1    except Indexerror, E:        print ' in indexerror except '        print e        return 2    except Zerodivisionerror, E:        print ' in Zerodivisionerror '        print e        return 3    else:        print ' no exception '        return 4    finally:        print ' in finally '        #return 5 ResultCode = excepttest () print ResultCode

The program output at this time:

This was a test of code path in try...except...else...finally********************************************************** **doing some work, and maybe exception'll be Raisedin indexerror exceptindex Errorin finally2

The return value becomes 2, this time a little puzzled, do not explain the problem first, we continue to look at other situations.

3. No exception occurred and the TRY statement block did not return

The code is as follows:

print ' This was a test of code path in try...except...else...finally ' print ' ********************************************* ' Def excepttest ():    try:        print ' doing some work, and maybe exception'll be raised '        #raise Ind Exerror (' index error ')        print ' After exception raise '        #return 0             except Keyerror, E:        print ' in Keyerror Except '        print e        return 1    except Indexerror, E:        print ' in indexerror except '        print e        return 2    except Zerodivisionerror, E:        print ' in Zerodivisionerror '        print e        return 3    else:        print ' no exception '        return 4    finally:        print ' in finally '        return 5 ResultCode = Excepttest () print ResultCode

This time the code output:

This was a test of code path in try...except...else...finally********************************************************** **doing some work, and maybe exception'll be Raisedafter exception Raiseno Exceptionin finally5

This verifies that if there is no exception then the Else statement is executed, and the finally statement executes, and then returns return 5 of the finally statement

But what happens when a return statement exists in a try statement block?

4. No exception occurs and the TRY statement block has a return statement

print ' This was a test of code path in try...except...else...finally ' print ' ********************************************* ' Def excepttest ():    try:        print ' doing some work, and maybe exception'll be raised '        #raise Ind Exerror (' index error ')        print ' After exception raise '        return 0             except Keyerror, E:        print ' in Keyerror Except '        print e        return 1    except Indexerror, E:        print ' in indexerror except '        print e        return 2    except Zerodivisionerror, E:        print ' in Zerodivisionerror '        print e        return 3    else:        print ' no exception '        return 4    finally:        print ' in finally '        return 5 ResultCode = Excepttest () print ResultCode

Execution Result:

This was a test of code path in try...except...else...finally********************************************************** **doing some work, and maybe exception'll be Raisedafter exception Raisein Finally5

Here else does not execute, and we have a conflict with the book knowledge, the Finally statement executes and returns 5.

Analysis: Because there is no exception, the return statement in the try block is executed, but finally must be executed, so the finally statement is executed before executing in try, and it can be assumed that the finally statement modifies the last returned value. The return value in try is modified to 5 and eventually returned, so the else statement is not executed.

5. An exception occurred and finally no return statement

print ' This was a test of code path in try...except...else...finally ' print ' ********************************************* ' Def excepttest ():    try:        print ' doing some work, and maybe exception'll be raised '        raise Inde Xerror (' index error ')        print ' After exception raise '        return 0             except Keyerror, E:        print ' in Keyerror Except '        print e        return 1    except Indexerror, E:        print ' in indexerror except '        print e        return 2    except Zerodivisionerror, E:        print ' in Zerodivisionerror '        print e        return 3    else:        print ' no exception '        return 4    finally:        print ' in finally '        #return 5 ResultCode = excepttest () print ResultCode

Execution Result:

This was a test of code path in try...except...else...finally********************************************************** **doing some work, and maybe exception'll be Raisedin indexerror exceptindex Errorin finally2

Because an exception occurred, so the return statement in the try must not be executed, then executed in the captured except, and a return statement exists in except, is it directly returned? Because the finally statement has to be executed, the return statement here needs to be put down for a while, go to finally to execute, and then return to except for execution after finnaly execution.

See here, we seem to have found some rules

1. If no exception occurs, there is a return statement in the try, there is no way to execute the code in the Else block, but if there is a return statement in the finally statement that modifies the final return value, I personally understand that return in try The statement modifies the value of the register when it is placed in a CPU register and then runs the finally statement, and finally returns the modified value in the return statement returned to the try.

2. If no exception occurs, there is no return statement in the try, then the code of the Else block is executed, but if there is return in else, then the finally code is executed first, and the change of the return value is consistent with the previous one.

3. If an exception occurs, the return statement in the try must not be executed, in the except statement that catches the exception, if there is a return statement, then the finally code is executed, and finally the code modifies the final return value, and then in the except The Retrun statement of the block returns the final modified return value, consistent with the first one.

Transferred from: http://www.2cto.com/kf/201405/304975.html

Python exception capture try except else finally has return execution order inquiry

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.