Saturday, July 28, 2012

Will finally blocks be executed if returning from try or catch blocks


Yes, the finally block is executed however the flow leaves the try block - whether by reaching the end, returning, or throwing an exception.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 change value result  
        result = 1;  
    }  
}
  
the value 4 will still be returned, not 1 .- the assignment in the finally block will have no effect the return result but it will be executed.A finally block will always be executed and this will happen before returning from the method, so you can safely write code

1 comment:

Anonymous said...

Good one