How to proper handling exceptions within a class library? RRS feed

  • Question

  • 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;
            sourceStream = File.OpenRead(sourceFileName);
            targetStream = new FileStream(targetFileName, FileMode.Create, FileAccess.Write);
            // ...
            // do something...
            // ...
            if (sourceStream != null)
                sourceStream = null;
            if (targetStream != null)
                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!


    • Edited by Vincenzo83 Tuesday, February 17, 2015 5:17 PM corrected spelling
    Tuesday, February 17, 2015 5:14 PM


  • Exceptions are kind of contract. once you defined what you throw it you can't add more, otherwise the caller may crash if you throw some new exceptions.  Also if you have too many possible causes of errors in a method, you may want to have your own exception class  (like SqlException) to give more context information (e.g. whether something wrong with reading the source file, or something wrong with writing the target file).  Of course you should do nothing about stackoverflow and out of memory exceptions. 

    Visual C++ MVP

    Tuesday, February 17, 2015 6:19 PM