Thought for the Dazed

I've had to give up that Distance Learning course as I was having trouble seeing the teacher.

Flickr
www.flickr.com
RobMiles' items Go to RobMiles' photostream
Twitter
C# Yellow Book

Search entire site
« Google Phone – Latest Developments | Main | Watch this, and then Watch it Again »
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;
    }
}

Reader Comments (4)

Nice question
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,
May 18, 2010 | Unregistered CommenterDennis
Going by your last post on try/catch, you said if an exception is thrown in the 'try' block then the code under 'catch' is executed. So it's pretty easy to see that an exception is most certainly being thrown inside the 'try' block, 99 wouldn't have been that bad a guess ;)

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.
May 18, 2010 | Unregistered CommenterPrabhu
99.

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.
May 18, 2010 | Unregistered CommenterJames
This would return 99, but result would end as 100 at the end of the programs lifespan!
May 19, 2010 | Unregistered CommenterCameron Wilby

PostPost a New Comment

Enter your information below to add a new comment.
Author Email (optional):
Author URL (optional):
Post:
 
All HTML will be escaped. Hyperlinks will be created for URLs automatically.