Question

What happens here ? I wonder whether SaveError() can be called after exception block ? Does the Main.cs get noticed about caught error? I want to see the story behind this case. What is the value of the variable "a" ? note: Asume there has been an error in try block.

Main.Cs

public void RunAll()
{
  ....
  int  a = doSubTask();
}

A.cs

public int doSubTask(){
try{
..
..
 return 1;
}catch(Exception Ex)
{
throw new AppException("Error", ex);
}
finally
{
   SaveError();
   return -1;
}
return 0;
}
Was it helpful?

Solution

The return 0; after the finally is redundant since finally will be called always even if there was an exception inside the cache or not.

Anyway, leaving the finally block with return will cause you a compilation error which means in your case, since you are throwing an exception from inside the catch block, a will not be set by any value.

OTHER TIPS

First of all, you can't return value within finally block, C# does not allow this.

finally always executes even if there are errors (i.e. control goes in catch block). So in your case, the return value will always be -1, it does not matter whether exception was thrown or not.

The last statement return 0; is non-reachable.

I guess you can modify your code like this. You shouldn't use more than one "return" key in a method.

    public int doSubTask()
    {
        int retval = 0;
        try
        {
            //to do
            retval = 1;
        }
        catch (Exception Ex)
        {
            SaveError();
            retval = -1;
            throw new AppException("Error", ex);
        }
        finally
        {
            // do something even there is error or not
        }
        return retval;
    }

Short answer: it depends from you machine ^^ As you can see in this MSDN article: http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx , if the exception is unhandled it's up to your system to decide if the Finally statement is executed or not.

Also: you can't return a value in a finally statement.

The whole method Foo seems a bit confusing to me. If your goal is to try a "risky" operation and handle the error you shouldn't rethrow the exception without having the outer code handle that.

So, if you want the RunAll method to know if there's been an error, you should set it's code inside a try-catch statement and rethrow the exception in the Foo method, without the finally statement so the rethrown exception "bubbles up" the chain and gets handled in the calling method :)

It is not allowed to try to "leave" a finally block, so it will not be valid to say return -1; inside the finally block. So your code will never compile.

error CS0157: Control cannot leave the body of a finally clause

Hence, there exists no question "what will happen when it runs".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top