Assume that you have a C# method with a return
statement inside a try
block. Is it possible to modify the return value in the finally
block?
The obvious approach, using return
in the finally
block, won't work:
String Foo()
{
try
{
return "A";
}
finally
{
// Does not compile: "Control cannot leave the body of a finally clause"
return "B";
}
}
Interestingly, this can be done in VB: Return
inside Finally
is forbidden, but we can abuse the fact that (probably for reasons of backwards compatibility) VB still allows the return value to be modified by assigning it to the method name:
Function Foo() As String ' Returns "B", really!
Try
Return "A"
Finally
Foo = "B"
End Try
End Function
Notes:
Note that I ask this question purely out of scientific curiosity; obviously, code like that is highly error-prone and confusing and should never be written.
Note that I am not asking about try { var x = "A"; return x; } finally { x = "B"; }
. I am aware that this doesn't change the return value and I understand why this happens. I'd like to know if there are ways to change the return value set inside the try block by means of a finally block.
Assume that you have a C# method with a return statement inside a try block. Is it possible to modify the return value in the finally block?
No.
You can however modify the return value outside the finally block:
static int M()
{
try
{
try
{
return 123;
}
finally
{
throw new Exception();
}
}
catch
{
return 456;
}
}
Just because there was originally a "return 123" does not mean that the method will return 123, if that's what your question is actually getting at. This method returns 456.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With