views:

37

answers:

2

I am developing a library for further usage in other libraries or final products. Let's say a user uses the library in a wrong way - passing an inappropriate value to a public function, calling functions in the wrong order etc.

In this case I might throw an exception, but these are usually designed for the final products and must be appropriately handled, while here we have a developer mistake who haven't read the documentation properly. On the other hand, he is the user of my library and thus assertion may be a wrong way to go (imagine an assertion that fired in the code that you have never written and expected just to work).

So far I have been using assertions only inside private internal functions and methods, thus notifying only me about my errors inside of the library. In the case of wrong usage by the library users I always throw an exception with an error description (and advice how to avoid it).

Do you think this is a right approach? If not, which rule of thumb are you using for assertions and exceptions when developing a library?

+2  A: 

Yes, this is right approach. Assertion is OK for internal use in a private functions. In the case client calls public method with incorrect parameters, exception should be thrown. Incorrect code must crash the program immediately, this is the best chance to fix the bug. It is a good idea to have different exception types for expected situations (file not found, device not responding etc.) and caller bugs like incorrect parameter value. Client code should catch expected exceptions, leaving unexpected exceptions unhandled. When unexpected exception is thrown, client program crashes, and programmer just fixes the bug.

However, if your library is written for internal use in the same company, it is OK to handle public method call errors like private, with assertions. But this approach must be strongly restricted and should not be used for external clients.

Alex Farber
A: 

Assertions will not work in Release assemblies, Exceptions is the only way to signal user of library that something is wrong

zabulus