C# Nested Try Catch statements or methods

cerror handlingmethods

Simple best practice question.

Should you nest try catch statements or just use methods.

For instance, if you have a method that opens a file does work and closes the file, you would have the open and close outside the try catch, or rather the close in the finally block.

Now if your open method fails, the method would assert right? So should your wrap that in a try catch block or should that be called from another method, which in turn as a try catch block?

Best Answer

In the context of a method that opens a file I would use a using statement vs a try catch. The using statement ensures that Dispose is called if an exception occurs.

using (FileStream fs = new FileStream(file, FileMode.Open))
{
    //do stuff
}

does the same thing as:

FileStream fs;
try
{
     fs = new FileStream(file, FileMode.Open);
     //do Stuff
 }
 finally
 {
        if(fs!=null)
           fs.Dispose();
 }