I am developing a wrapper for a third party function library that is interfacing with some special hardware. So basically, I want to encapsulate the dll functions (bool Connect(), void Disconnect() etc) in a MyHardwareObject with connect- and disconnect methods.
The Connect function from the dll can throw some specific exceptions, for example when the hardware is not present. For the application, the information on why the connect method failed is considered unimportant, so the additional information contained in the exception is not needed.
What is the best way of handling those exceptions, returning false, or leaving the exception unhandled here and catch it on the level that would otherwise handle the fact that the connect method returnded false?
bool MyHardwareObject.Connect() { try { ThirdPartyLibrary.Connect(); } catch (SomeException) { return false; } return true; }
As opposed to
bool MyHardwareObject.Connect() { ThirdPartyLibrary.Connect(); return true; }
(or in the second case better void MyHardwareObject.Connect(), since we either return true, or throw an exception?)
Or what else would you do? And most important: Why?
It’s really difficult to choose wisely between exceptions and return codes. It depends on a lot of things, and how errors are handled in the rest of your codebase would be the most important one – stay consistent.
Lately, I’m leaning more towards the ‘don’t throw an exception if it’s not worth it’. Our exceptions do a lot of work: they log stuff, they create stack traces, etc. If I just want to convert a string to an integer, throwing an exception if the input string has the wrong format is probably not worth it. On the other hand, I have objects that I simply don’t want in my system if they can’t be constructed from proper data, and in that case their constructors throw exceptions.
If the rest of the codebase does not give you any hint on how to do it, I like this rule of thumb: imagine that throwing an exception makes your computer emit a loud beep. As long as you can put up with it, throwing is fine.