3

In C#.NET, let's take the following example

[WebMethod]
public int TakeAction()
{
    try {
        //Call method A
        Return 1;
    } catch (Exception e) {
        //Call method B
        Return 0;
    } finally {
        //Call method C
    }
}

Now let's say method C is a long running process.

Does the client who invokes TakeAction get back the return value, before method C is invoked, or after it is invoked / completed?

adam
  • 2,930
  • 7
  • 54
  • 89

2 Answers2

11

The return value is evaluated first, then the finally block executes, then control is passed back to the caller (with the return value). This ordering is important if the expression for the return value would be changed by the finally block. For example:

Console.WriteLine(Foo()); // This prints 10

...

static int Foo()
{
    int x = 10;
    try
    {
        return x;
    }
    finally
    {
        // This executes, but doesn't change the return value
        x = 20;
        // This executes before 10 is written to the console
        // by the caller.
        Console.WriteLine("Before Foo returns");
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Additionally, even though the Return is [Evaluated] before the finally block.... my main question is to find out at what point does the caller receive back the return / response? Before or After the finally has executed? – adam Oct 23 '13 at 21:41
  • 1
    @adam: After the finally block has executed - that's what I mean by "control is passed back to the caller". It's easy to check this - just run the code I've shown. It will print "Before Foo returns" before it prints 10. – Jon Skeet Oct 23 '13 at 21:43
  • Sure does, Thanks Jon! I expect this works the same way for Web Services, then? – adam Oct 23 '13 at 21:45
  • @adam: Yes. It's a fundamental part of the language, which will be the same for any use. – Jon Skeet Oct 23 '13 at 21:50
2

anything in finally block is executed after leaving try block. In your case it either returns 1 or 0 and then executes method c. for more info on try-catch-finally you can refer this

fcmaine
  • 359
  • 2
  • 5
  • 17
  • Returns 1 , then executes method C..... The other answer on this post is the opposite..... Return evaluated -- Finally executes -- Then, control passed back to caller..... not sure what to believe =\ – adam Oct 23 '13 at 21:39
  • No, the control returns to the caller *after* method C. That may be what you meant, but it's not clear from your answer. – Jon Skeet Oct 23 '13 at 21:43
  • 2
    @adam: If in doubt, trust Jon Skeet. But the key (which isn't explicitly stated in this answer) is that control doesn't return to the caller until after the finally block is executed. – Colin DeClue Oct 23 '13 at 21:44
  • Yes. Control returns after executing method c but return value is set in try block and doesn't change. Apologies if I misdirected. – fcmaine Oct 23 '13 at 21:45