Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
735 views
in Technique[技术] by (71.8m points)

exception handling - Will finally blocks be executed if returning from try or catch blocks in C#? If so, before returning or after?

No content available!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, the finally block is executed however the flow leaves the try block - whether by reaching the end, returning, or throwing an exception.

From the C# 4 spec, section 8.10:

The statements of a finally block are always executed when control leaves a try statement. This is true whether the control transfer occurs as a result of normal execution, as a result of executing a break, continue, goto, or return statement, or as a result of propagating an exception out of the try statement.

(Section 8.10 has a lot more detail on this, of course.)

Note that the return value is determined before the finally block is executed though, so if you did this:

int Test()
{
    int result = 4;
    try
    {
        return result;
    }
    finally
    {
        // Attempt to subvert the result
        result = 1;
    }
}

... the value 4 will still be returned, not 1 - the assignment in the finally block will have no effect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...