I wrote the following test code, even though I was pretty sure what would happen:
static void Main(string[] args)
{
Console.WriteLine(Test().ToString());
Console.ReadKey(false);
}
static bool Test()
{
try
{
try
{
return true;
}
finally
{
throw new Exception();
}
}
catch (Exception)
{
return false;
}
}
Sure enough, the program wrote "False" to the console. My question is, what happens to the true that is originally returned? Is there any way to get this value, in the catch block if possible, or in the original finally block if not?
Just to clarify, this is only for educational purposes. I would never make such a convoluted exception system in an actual program.
Some resource cleanup, such as closing a file, needs to be done even if an exception is thrown. To do this, you can use a finally block. A finally block always executes, regardless of whether an exception is thrown. The following code example uses a try / catch block to catch an ArgumentOutOfRangeException.
Yes, the finally block will be executed even after a return statement in a method.
When catch and finally block both return value, method will ultimately return value returned by finally block irrespective of value returned by catch block.
Yes, we can write a return statement of the method in catch and finally block. There is a situation where a method will have a return type and we can return some value at any part of the method based on the conditions.
No, it's not possible to get that value, because only a bool
is returned, after all. You can set a variable, though.
static bool Test()
{
bool returnValue;
try
{
try
{
return returnValue = true;
}
finally
{
throw new Exception();
}
}
catch (Exception)
{
Console.WriteLine("In the catch block, got {0}", returnValue);
return false;
}
}
It's messy, though. And for education purposes, the answer is no.
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