How to use finally block correctly with catch blocks? [duplicate]

I'm a newbie to exception handling in C#, just a question on how to use finally block correctly, I saw following code in a book:

public sealed class SomeType {
   public void ReadFile() {
      FileStream fs = new FileStream(@"C:\Data.bin ", FileMode.Open);
      try {
         // Display 100 divided by the first byte in the file.
         Console.WriteLine(100 / fs.ReadByte());
      }
      finally {
         // Put cleanup code in a finally block to ensure that the file gets closed regardless
         // of whether or not an exception occurs (for example, the first byte was 0).
         if (fs != null) 
            fs.Dispose();
      }
   }
}

I think there is a problem in this code, if you just call this method directly, it might throw an exception, and since there is no catch block, it is an unhandled exception, so the process will terminate and the finally block won't execute.

So you have to call this method indirectly with another method that has catch block as:

class Program {
   static void Main(string[] args) {
      WrappedMethod();
   } 

   static void WrappedMethod() {
      try {
         new SomeType.ReadFile();
      }
      catch (DivideByZeroException e) {
         ...
      }
   }
}

But not all developers will use a wrapped method with try-catch block, when they sees SomeType.ReadFile() method they probably think "oh, I can call this method to read file" without thinking any possible exception that this method might bring (the source code of SomeType might not availble as it might be in a third party library).

So isn't it more appropriate for ReadFile() method to have its own catch block as:

public sealed class SomeType {
   public void ReadFile() {
      FileStream fs = new FileStream(@"C:\Data.bin ", FileMode.Open);
      try {
         // Display 100 divided by the first byte in the file.
         Console.WriteLine(100 / fs.ReadByte());
      }
      catch (DivideByZeroException e) {
         ...
      }
      finally {
         // Put cleanup code in a finally block to ensure that the file gets closed regardless
         // of whether or not an exception occurs (for example, the first byte was 0).
         if (fs != null) 
            fs.Dispose();
      }
   }
}


from Recent Questions - Stack Overflow https://ift.tt/31pJoaZ
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)