C#错误代码与异常

joh*_*ohn 6 c# error-handling

我有一个控制电路,我通过串口进行通信.如果响应命令与某种格式不匹配,我认为它是一个错误,并想知道我是否应该返回错误代码或抛出异常?例如:

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.
       ...
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Jon*_*eet 8

几乎所有情况下,我都会通过异常传达错误.我几乎从不使用"错误代码" - 有时候将结果与成功/失败一起使用是有用的int.TryParse,但我不认为这种情况是这样的.这听起来像一个真正的错误条件,应该停止进一步的进展,所以一个例外是适当的.

编辑:如评论中所述,如果报告错误的电路确实是"预期的"并且调用者应该能够处理它并且应该主动寻找那种情况,那么使用状态代码是合理的.

不幸的是,错误处理是我们在软件工程中还没有真正做到的事情之一......