Question

I am C# developer and I'd like to use factory pattern to create objects that represent file or directory on hard disk. FileInfo and DirectoryInfo are classes in .NET used for that purpose but instead of them I'd like to have my own IFileInfo and IDirectoryInfo interfaces that wraps them. The reason for using custom interfaces rather than built in classes is because I'd like to add some additional properties such as file shell icon etc...

So I'd like to use factory pattern to create instances of IFileInfo and IDirectoryInfo for a given string of a file/directory path.

So factory class would look something like:

public class MyFileInfoFactory
{
    IFileInfo Create(string filePath)
    {
        System.IO.FileInfo file = new System.IO.FileInfo(filePath);

        // turn FileInfo to my IFileInfo etc...
    }
}

Now looking at System.IO.FileInfo docs (FileInfo MSDN) I see there are several possible exceptions that can be thrown. My question is should I handle all these exceptions in the factory Create() method? Or should I let them propagate upwards to whichever code is calling MyFileInfoFactory.Create()?

If first solution is way to go, then what would be the next step? For example should I return null or possibly throw some custom exception with InnerException property set to the actual exception thrown from new FileInfo() constructor?

Just wondering what would be the best practice in this concrete scenario case...

Was it helpful?

Solution

You should handle an exception, in general, under two circumstances:

  1. You know how to handle it and recover from the error. Without any outside intervention, and you wish to do so in a manner than is transparent to the calling code.
  2. You want to wrap the exception in your own exception. This is useful if you need to communicate additional information to the calling code or if the particular exception might not be terribly important to the calling code (though you should always include it as the innerException parameter in the exception's constructor).

So, for any of the exceptions that could be thrown (and don't consider the exception list in MSDN to be exhaustive...a lot of that stuff is boilerplate, unfortunately), if you don't know how to recover from it silently and don't want to wrap it in your own exception, then don't handle it and let it bubble up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top