I have a control circuit that I communicate with via serial port. If the response command doesn't match a certain format I consider it to be an error and was wondering if I should return an error code or throw an exception? For example:
public double GetSensorValue(int sensorNumber)
{
...
string circuitCommand = "GSV,01," + sensorNumber.ToString(); // Get measurement command for specified sensor.
string responseCommand;
string expectedResponseCommand = "GSV,01,1,OK";
string errorResponseCommand = "ER,GSV,01,1,62";
responseCommand = SendReceive(circuitCommand); // Send command to circuit and get response.
if(responseCommand != expectedResponseCommand) // Some type of error...
{
if(responseCommand == errorResponseCommand) // The circuit reported an error...
{
... // How should I handle this? Return an error code (e.g. -99999) or thrown an exception?
}
else // Some unknown error occurred...
{
... // Same question as above "if".
}
}
else // Everything is OK, proceed as normal.
...
}
Thanks!
In almost all cases I would communicate errors via exceptions. I would almost never use "error codes" as such - occasionally it's useful to give success/failure along with a result as in int.TryParse
etc, but I don't think this situation works like that. This sounds like a real error condition which should stop further progress though, so an exception is appropriate.
EDIT: As noted in comments, if the circuit reporting an error really is "expected" and the caller should be able to deal with it and should actively be looking for that situation, then it's reasonable to use a status code.
Unfortunately error handling is one of those things that we haven't really got right in software engineering yet...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With