I read the article Vexing exception about exception handling and I understand the guidelines to determine which exceptions you need to catch and handle, but I would like to better understand how to work with exceptions when developing a library for distribution to third parties.
Suppose that I'm developing a library that needs to read a file and to write another file in order to implement its functionality.
public void DoSomething(string sourceFileName, string targetFileName) { FileStream sourceStream = null; FileStream targetStream = null; try { sourceStream = File.OpenRead(sourceFileName); targetStream = new FileStream(targetFileName, FileMode.Create, FileAccess.Write); // ... // do something... // ... } catch { throw; } finally { if (sourceStream != null) { sourceStream.Close(); sourceStream.Dispose(); sourceStream = null; } if (targetStream != null) { targetStream.Close(); targetStream.Dispose(); targetStream = null; } } }
Since the above method is a method of a class library, and since I have no way to handle any exceptions that may occur during the opening of a stream, then it is appropriate to re-throw them: after all, the user layer developers could handle these exceptions by displaying an error message to the user.
Consider again the method that I just wrote and suppose that the statements after opening the stream invoke a method of an external library: this library may be loaded at runtime within a plugin architecture, so I am not able to know what exceptions could be launched by the method of this external library. How to deal with this situation?
Thanks a lot for your support!
Vincenzo