I've been pondering this problem for a while now and find myself continually finding caveats and contradictions, so I'm hoping someone can produce a conclusion to the following:
Favour exceptions over error codes
As far as I'm aware, from working in the industry for four years, reading books and blogs, etc. the current best practice for handling errors is to throw exceptions, rather than returning error codes (not necessarily an error code, but a type representing an error).
But - to me this seems to contradict...
Coding to interfaces, not implementations
We code to interfaces or abstractions to reduce coupling. We don't know, or want to know, the specific type and implementation of an interface. So how can we possibly know what exceptions we should be looking to catch? The implementation could throw 10 different exceptions, or it could throw none. When we catch an exception surely we're making assumptions about the implementation?
Unless - the interface has...
Some languages allow developers to state that certain methods throw certain exceptions (Java for example, uses the
throws keyword.) From the calling code's point of view this seems fine - we know explicitly which exceptions we might need to catch.
But - this seems to suggest a...
Why should an interface specify which exceptions can be thrown? What if the implementation doesn't need to throw an exception, or needs to throw other exceptions? There's no way, at an interface level, to know which exceptions an implementation may want to throw.
Why are exceptions preferred when they seem (in my eyes) to contradict software best practices? And, if error codes are so bad (and I don't need to be sold on the vices of error codes), is there another alternative? What is the current (or soon to be) state of the art for error handling that meets the requirements of best practices as outlined above, but doesn't rely on calling code checking the return value of error codes?