Statement against exclusion in library design

I am developing a library for future use in other libraries or end products. Let's say the user uses the library incorrectly, passing an invalid value to a public function, calling the functions in the wrong order, etc.

In this case, I could throw an exception, but they are usually intended for the final products and should be handled accordingly, while here we have a mistake from developers who did not read the documentation properly. On the other hand, he or she is a user of my library and, therefore, a statement may be the wrong way (imagine a statement, burned in code that you never wrote and was expected to only work).

So far, I have used statements only inside private internal functions and methods, thereby only reporting my errors inside the library. In case of improper use of the library by users, I always throw an exception with a description of the error (and advice on how to avoid it).

Do you think this is the right approach? If not, what rule of thumb do you use for statements and exceptions when designing a library?

+4
source share
2 answers

Yes, this is the right approach. Approval is in order for internal use in private functions. In the case when the client calls a public method with incorrect parameters, an exception should be thrown. Wrong code should immediately terminate the program, this is the best chance to fix the error. It is a good idea to have different types of exceptions for expected situations (file not found, device not responding, etc.) And caller errors, such as an incorrect parameter value. Client code should catch expected exceptions, leaving unforeseen exceptions unhandled. When an unexpected exception is thrown, the client program crashes, and the programmer simply fixes the error.

However, if your library is written for internal use in the same company, it is quite normal to handle public method invocation errors, such as private, with statements. But this approach should be strictly limited and should not be used for external clients.

+5
source

Assertions will not work in Release assemblies; Exceptions are the only way to tell the library user that something is wrong.

+1
source

All Articles