C#错误代码与异常 [英] C# Error Code vs. Exception

查看:646
本文介绍了C#错误代码与异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  public double GetSensorValue(int sensorNumber)
{
...
string circuitCommand =GSV,01,+ sensorNumber.ToString(); //获取指定传感器的测量命令。
string responseCommand;
string expectedResponseCommand =GSV,01,1,OK;
string errorResponseCommand =ER,GSV,01,1,62;

responseCommand = SendReceive(circuitCommand); //发送命令到电路并获得响应。

if(responseCommand!= expectedResponseCommand)//某些类型的错误...
{
if(responseCommand == errorResponseCommand)//电路报告错误...
{
... //我该怎么处理这个?返回错误代码(例如-99999)或抛出异常?
}
else //发生一些未知错误...
{
... //与上述if相同的问题。
}
}
else //一切正常,正常进行。
...
}

谢谢!

解决方案

在几乎所有的案例中,我将通过异常传递错误。我几乎永远不会使用错误代码,因为在 int.TryParse 等中给出成功/失败以及结果是有用的,但我不认为这种情况就是这样。这听起来像是一个真正的错误条件,应该停止进一步的进步,所以一个例外是适当的。



编辑:如评论中所指出的,如果报告错误的电路真的是预期,呼叫者应该能够处理它,并应积极寻找这种情况,那么使用状态代码是合理的。



不幸的是,错误处理是其中一件事我们在软件工程方面还没有真正适合...


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...

这篇关于C#错误代码与异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆