Tuesday
May182010
Final Exception Funny

Think you know about exceptions? What would this method return?
static int funAndGames()
{
int result = 99;
try
{
throw new Exception("Boom");
}
catch
{
return result;
}
finally
{
result = 100;
}
}


in
Software

Reader Comments (4)
At the first glance would say 100, but i'm going for 99. Makes me wonder when you want to use a structure like this. Have to admit it's a great example.
Kind regards,
Another thing that I found interesting is, first, when I looked at this code, I thought the compiler would whine saying "not all paths have a return value" because there was a return statement missing at the end. But on trying it out the compiler didn't complain. If you put the throw statement inside an 'if(ret > 50)', the compiler reports that error. So turns out the compiler is smart enough to see that, in this case, all paths do indeed have a return value.
The finally block will fire and change the int to 100, but after it has returned the value of 99? I'm guessing this happens because finally will always fire after catch.