March 11, 2011
try…success…catch…finally block wanted in C#

Yesterday I complained about wanting such a block in C#. Why? Here’s the situation (not too common, but it happens):

try
{
    OpenTheFridgeAndTakeChocolate();
    CutChocolateIntoPieces();
}
catch (SomethingFailedException ex)
{
    GoToChocolateStore();
}
finally
{
    CloseTheFridge();
}

The problem I’m having is that I only want to go to store if I cannot find the chocolate in the fridge. Right now I’d go to the store even if I cut myself with the knife, because the catch block doesn’t differentiate between the two operations in the try block.

There are several ways to deal with this situation:

Separate exceptions

try
{
    OpenTheFridgeAndTakeChocolate();
    CutChocolateIntoPieces();
}
catch (SomethingFailedException ex)
{
    GoToChocolateStore();
}
catch (ChocolateCuttingException ex)
{
    // do something here
}
finally
{
    CloseTheFridge();
}

this one isn’t really a good option in my particular case because I have to cover a wide variety of cases when the chocolate taking fails, so my exception is pretty high in the inheritance hierarchy. Also, I don’t really want to handle the ChocolateCuttingException here.

Nested Blocks And Flags

try
{
   bool chocolateTaken = false;
   try
   {
      OpenTheFridgeAndTakeChocolate();
      chocolateTaken = true;
   }
   catch (SomethingFailedException ex)
   {
      GoToChocolateStore();
   }

   if (chocolateTaken)
      CutChocolateIntoPieces();
}
finally
{
    CloseTheFridge();
}

This seems cumbersome, it would be much easier to type something like:

try
{
    OpenTheFridgeAndTakeChocolate();
}
success
{
    CutChocolateIntoPieces();
}
catch (SomethingFailedException ex)
{
    GoToChocolateStore();
}
finally
{
    CloseTheFridge();
}

9:57am  |   URL: http://tmblr.co/Zm5Djx3XP1OH
  
Filed under: csharp 
  1. braincrunch posted this