Error Handling – Best Practices for External Libraries in .NET

error handlinglibrariesnet

My development environment specifically is .NET and I'm writing a DLL to be compiled and referenced in other .NET programs we'll be writing going forward.

My question is: In that DLL, what is the best practice for error handling? If you have a function doSomething(value) and it fails, do you throw an exception? Or do you return a boolean indicating success/failure and have an instance variable that you check for the error message?

Best Answer

In old times, before the invention of exceptions, the most painful thing about coding was to stop your program from blindly continuing after some API call failed. You had to check every single function-call result for being NULL, -1 or whatever the designer chose as his signal of failure, and then to return from your function with your failure-signalling value. Things like this (e.g. in C):

FILE *fp = fopen(...);
if (fp == NULL) {
    return -1;
}

One productive line of code, three ugly, boilerplate ones.

When using exceptions, this comes for free. So, wherever technically possible, use exceptions to signal failures (but not everything is a failure, e.g. when searching for a substring in a string, not finding it shouldn't throw as that's normal). Without exceptions, you're forcing your colleagues into this ugly coding style.

And put information about the failure into the exception object, if it isn't automatically included, e.g. the file name when trying to open a file, so the sysadmin reading the log knows where to search for the problem.

When consuming REST services, I'd recommend to wrap failure codes in exceptions if your REST library doesn't already do that.