Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access the value returned by a function in a finally block

Tags:

c#

.net

I'd like to know if it is possible to get the return value of a function inside a finally block.

I have some code that is like this.

try
{
    return 1;
}
finally
{
    //Get the value 1
}

I know it's possible by adding a variable that can hold the returned value. But I was wondering if it was possible to get the value in any way.

Thanks

like image 883
Patrick Parent Avatar asked Mar 01 '10 21:03

Patrick Parent


People also ask

What happens if we return from finally block?

Returning from inside a finally block will cause exceptions to be lost. A return statement inside a finally block will cause any exception that might be thrown in the try or catch block to be discarded.

Can we return value in finally block?

Yes, we can write a return statement of the method in catch and finally block.

What will happen when try and finally block both return value?

When try and finally block both return value, method will ultimately return value returned by finally block irrespective of value returned by try block.

What happens if there is a return statements in both the try block and finally block in a function?

If the return in the try block is reached, it transfers control to the finally block, and the function eventually returns normally (not a throw).


2 Answers

No, you can't do that.

like image 187
David Morton Avatar answered Sep 23 '22 07:09

David Morton


int value = -1;

try 
{ 
    value = 1; 
} 
finally 
{ 

    // Now the value is available
} 

return value;
like image 39
duffymo Avatar answered Sep 23 '22 07:09

duffymo