Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does a finally block execute if the catch block contains a continue statement?

I have some code that looks like this:

foreach(var obj in collection)
{
   try
   {
      // WriteToFile returns the name of the written file
      string filename = WriteToFile(obj); 
      SendFileToExternalAPI(filename);
   }
   catch ( ArbitraryType1Exception e )
   {
      LogError(e);
      continue;
   }
   ...
   catch ( ArbitaryTypeNException e )
   {
      LogError(e);
      continue;
   }
   finally
   {
      try
      {
         File.Delete(filename);
      }
      catch (Exception e)
      {
         LogError(e);
      }
   }
}

The objective is to try and write out a temporary file for each object in the collection, attempt to load that file into an external API which wants filenames, and then clean up the temporary files when done. If an error happens when writing the file out to disk or loading it to the external API, I just want to log the error and move on to the next object; I can't ask the user what to do.

I'm a bit uncertain of how the timing of finally blocks work when you have continue statements in the catch handlers. Is this code going to (attempt to) delete the correct file no matter whether an exception is thrown in the try block? Or do the continues in the catch statements take effect before the finally block runs?

like image 301
Hydrargyrum Avatar asked Jun 26 '12 03:06

Hydrargyrum


1 Answers

Think of it as a try/finally block with catch expressions optional. Both continue statements in your code would pop the execution stack out of the catch which would place execution in the finally block before allowing the loop to continue. Any time there is a try/finally block, finally will always be executed.

like image 145
EdFred Avatar answered Sep 29 '22 10:09

EdFred