What is a 'good number' of exceptions to implement for my library?

Posted by Fuzz on Programmers See other posts from Programmers or by Fuzz
Published on 2011-11-06T13:47:35Z Indexed on 2013/10/18 10:15 UTC
Read the original article Hit count: 240

Filed under:
|

I've always wondered how many different exception classes I should implement and throw for various pieces of my software. My particular development is usually C++/C#/Java related, but I believe this is a question for all languages.

I want to understand what is a good number of different exceptions to throw, and what the developer community expect of a good library.

The trade-offs I see include:

  • More exception classes can allow very fine grain levels of error handling for API users (prone to user configuration or data errors, or files not being found)
  • More exception classes allows error specific information to be embedded in the exception, rather than just a string message or error code
  • More exception classes can mean more code maintenance
  • More exception classes can mean the API is less approachable to users

The scenarios I wish to understand exception usage in include:

  • During 'configuration' stage, which might include loading files or setting parameters
  • During an 'operation' type phase where the library might be running tasks and doing some work, perhaps in another thread

Other patterns of error reporting without using exceptions, or less exceptions (as a comparison) might include:

  • Less exceptions, but embedding an error code that can be used as a lookup
  • Returning error codes and flags directly from functions (sometimes not possible from threads)
  • Implemented an event or callback system upon error (avoids stack unwinding)

As developers, what do you prefer to see?

If there are MANY exceptions, do you bother error handling them separately anyway?

Do you have a preference for error handling types depending on the stage of operation?

© Programmers or respective owner

Related posts about design-patterns

Related posts about exceptions