I don't understand the best practices about when a method should throw an exception or return an error code / boolean
result.
Specifically, I have this situation: There is a thread that is polling a device (retrieving its status) every 30 seconds.
If the device is not reachable, the application must not stop, since it does not need to be able to communicate with the mentioned device to perform all the other operations it does.
So, in general, the thread code is like the following:
while(true)
{
device.connect();
string st = device.getStatus();
updateStatus(st);
device.disconnect();
sleep(30);
}
Currently, the connect()
method throws an exception if the device is not online.
I think that, in this situation, maybe it is a better practice to make the connect()
method to return a boolean result in order to report whether or not the device is reachable, but I am not sure at all.
The above would look like this:
while(true)
{
if(device.connect())
{
string st = device.getStatus();
device.disconnect();
updateStatus(st);
}
sleep(30);
}
Actually, when the application is in production, the device "should" be always online, that makes me think the best option is an exception.
On the other hand, the application can keep the execution perfectly without communciating with the device. The only consequence of it not being connected is that the functionallity associated to it is disabled. This is what makes me think that the boolean
return value is better.
If the device is not connected, I will have a thread throwing an exception every 30 seconds. Even if the exception is catched, is this admissible in terms of software engineering good practices?