Finally will execute, even after return

7 January, 2009 § Leave a comment

How’s this for weird looking code?

public static void RunSnippet()
    var y = testFinally();
    if( y == 99 )
        WL("It is 99");
        WL("It is 6");

public static int? testFinally()
    int? x = 99;
        return x;
        x = 6;   
    return x;

What happens? testFinally will return 99. If you changed the finally block to set x equal to null, the same result will happen. When there is a finally block, the function will not return until after the finally block has finished, regardless of any code following it. The second return statement is never reached. Also, you cannot return from a finally block, since control flow statements cannot be made in a finally block.

The code above was written with SnippetCompiler, a really nice free tool to have at your side when you want to test something out but don’t want to create a new solution in Visual Studio.

Tagged: ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Finally will execute, even after return at JAWS.



Get every new post delivered to your Inbox.

Join 1,040 other followers