自从确定以返回异常? [英] Ever OK to Return an Exception?

查看:126
本文介绍了自从确定以返回异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要读各种传感器和处理数据的方法。在这些方法我有一个通过串口(获取传感器值)命令发送到电路的其他方法。可能会出现通信错误,我想知道,如果它是有史以来确定返回例外呢?例如:

I have methods to read various sensors and process data. Within these methods I have other methods that send commands to a circuit via serial port (to get the sensor values). A communication error may occur and I was wondering if it is ever OK to "return" an exception? For example:

public double AverageSensorValues()
{
  try
  {
   ...
   double sensor1Value = SensorValue(1);
   double sensor2Value = SensorValue(2);
   ...
   }
   catch (Exception ex)
   {
      MessageBox.Show("Error in AverageSensorValues()");
   }
}

public double SensorValue(int sensorNum)
{
   try {

   // Send command to circuit to return value.
   string response = SendCommand(commandStringToGetValue);

   // Check to see if response is an error
   bool isError = ErrorReturned(response);

   if(isError)
      ProcessError(response);  // Throws exception.

   ... // Other things that could cause exceptions to be thrown.

   }
   catch (Exception ex)
   {
      throw new Exception("Error in SensorValue()", ex);
   }
}

public void ProcessError(string errorResponse)
{
   // Split string and get error parameters (#, input command, etc.)

   throw new Exception(String.Format("Error-{0}: See ...", errorNumber));  // Is this OK? More readable than "ER,84,DM,3L" for example.
}

这是以往任何时候都好或者是它被认为是不好的做法?

Is this ever OK or is it considered "bad practice"?

谢谢!

修改

好吧,我读了不同的反应,它看起来像我这样做是完全错误的(裸陪我,我一个机甲。ENG)。我试图使用上述作为一个简单的例子,但它看起来像我刚刚张贴从一开始走的全部细节。因此,这里是我的情况更详细的例子:

Okay, I read over the various responses and it looks like I am doing this completely wrong (bare with me I'm a mech. eng.). I attempted to use the above as a quick example but it looks like I should have just posted the full details from the get-go. So here is a more detailed example of my situation:

public double[] GetHeightAtCoords(CoordClass[] coords)  // Get height measurement at various positions. Called after button click, results are displayed on UI.
{
   try  // Error could occur within one of these methods. If it does, not Program critical but it should notify user and not return any result.
   {
   for(int coordIndex = 0; coordIndex < coords.Length; coordIndex++)  // Cycle through each desired position.
   {
      ...
      currentCoords = GetCurrentCoords();   // Get current actuator position.
      ... //Update UI.
      MoveToCoords(coords[coordIndex]);   // Move actuator to position.
      currentCoords = GetCurrentCoords(); // Verify position.
      EngageBrake();   // Lock actuator in place.
      double height = GetHeight(); // Read sensor data.
      ReleaseBrake();   // Release brake.
      ...
   }
  }
  catch (Exception ex)
  {
     // Display in statusbar.
     statusBar1.Text = String.Format("Error in GetHeightAtCoords(): {0}", ex.Message);
  }

   ...
   return heights;  // Return position heights array.
}

public CoordClass GetCurrentCoords()   // Method to read positional encoder values.
{
   ...
   try
   {
   double xPosition = GetXEncoderValue();   // Return x-coord value.
   double yPosition = GetYEncoderValue();   // Return y-coord value.
   }
   catch (Exception ex)
   {
      throw new Exception("Error in GetCurrentCoords(): {0}", ex.Message);
   }
   ...
   return new CoordClass(xPosition, yPosition); // Return current coords.
}

public void MoveToCoords(CoordClass coord)   // Method to move actuators to desired positions.
{
   try
   {
   ... 
   currentCoords = GetCurrentCoords(); // See where actuators are now.
   ... // Setup movement parameters.
   MoveToX(coord.X);   // Move x-axis actuator to position.
   MoveToY(coord.Y);   // Move y-axis actuator to position.
   }
   catch (Exception ex)
   {
      throw new Exception("Error in MoveToCoords(): {0}", ex.Message);
   }
   ...
}

public double GetXEncoderValue()   // Method to return x-coord value.
{
   string getXCoordCommand = "SR,ML,01,1";   // Serial command to get x-coord.
   ...
   string controllerResponse = SendReceive(getXCoordCommand);  // Send command, get response command.

   if(!ResponseOK(controllerResponse))   // If the response doesn't match the "command OK" response (i.e. SR,ML,01,1,OK)...
   {
      if(IsErrorResponse(controllerResponse))  // See if response is an error response (e.g. command error, status error, parameter count error, etc.)
         // Some known error type occurred, cannot continue. Format error string (e.g. ER,SRML,61) to something more meaningful and report to user (e.g. Read X Value Error: Status error.).
         throw new Exception("Read X Value Error-{0}: {1}", errorNumber, (ErrorEnum)errorNumber);
      else
         // Something else went wrong, cannot continue. Report generic error (Read X Value Error.).
         throw new Exception("Read X Value Error.");
   }
   ...
}

// GetYEncoderValue(), MoveToX(), MoveToY(), GetHeight(), EngageBrake() and ReleaseBrake() follow the same format as EngageBrake().

下面是我的逻辑,如果...

Here was my logic, if...

来电订购:GetHeightAtCoords() - > MoveToCoords() - > GetCurrentCoords() - > GetXEn coderValue(),与控制器响应误差

Call order: GetHeightAtCoords() -> MoveToCoords() -> GetCurrentCoords() -> GetXEncoderValue(), error with controller response.

在GetXEn codeR抛出新的异常(),渔获量GetCurrentCoords(),然后重新抛出新的异常,赶在MoveToCoords(),然后重新抛出新的异常,赶在GetHeightAtCoords()和显示信息状态栏(消息=,在GetHeightAtCoords错误():在MoveToCoords错误():在GetCurrentCoords错误():读X值误差-6:状态错误)。

Throw new Exception within GetXEncoder(), catch in GetCurrentCoords() and re-throw new Exception, catch in MoveToCoords() and re-throw new Exception, catch in GetHeightAtCoords() and display message in status bar (message = "Error in GetHeightAtCoords() : Error in MoveToCoords() : Error in GetCurrentCoords() : Read X Value Error-6: Status Error").

由于GetXEn codeR()可以从一个方法中的多个位置调用,我计算过,如果我让原始异常泡一路上涨这将是帮助不大的用户(在GetHeightAtCoords如错误():读X值误差-6:状态错误,这一次)?拿这个例子,它读取X值失败了吗? GetHeightAtCoords() - > MoveToCoords() - > GetCurrentCoords() - > GetXEn coderValue()或GetHeightAtCoords() - > GetCurrentCoords() - > GetXEn coderValue()

Because GetXEncoder() can be called from multiple places within a method, I figured that if I let the original exception bubble all the way up it would be of little help to the user (e.g. "Error in GetHeightAtCoords() : Read X Value Error-6: Status Error", which time?). Take this example, which Read X Value failed? GetHeightAtCoords() -> MoveToCoords() -> GetCurrentCoords() -> GetXEncoderValue() OR GetHeightAtCoords() -> GetCurrentCoords() -> GetXEncoderValue() ?

希望这是更明确:/

是这样做过?你会如何​​建议我继续吗?再次感谢大家对你的输入!

Is something like this ever done? How would you recommend I proceed? Thanks again Everyone for your input!

推荐答案

制作总是抛出一个异常是有点不好闻的方法。它看起来像一个处理错误,然后继续进行。我宁愿做这样的:

Making a method that always throws an exception is a bit bad smelling. It looks like that processes the error and then continues on. I would rather do it like this:

if(isError)
      throw MakeMeAnException(response);  
...
}

public Exception MakeMeAnException(string errorResponse)
{
   // Split string and get error parameters (#, input command, etc.)
   return new MyException(String.Format("Error-{0}: See ...", errorNumber)); 
}

这使得它非常清楚, IF(ISERROR)的结果总是抛出;在原来的版本,它是很难看到它了。

That makes it very clear that the if (isError) consequence always throws; in your original version it is hard to see that it does that.

此外,一个异常的堆栈跟踪设定在这样的地步,是的抛出的,所以这台,其中检测到错误,没有的地步,唯一的例外是堆栈跟踪点构造,这似乎是更好的。

Also, the stack trace of an exception is set at the point where it is thrown, so this sets the stack trace to the point where the error is detected, not the point where the exception is constructed, which seems better.

有在code还有更多的不良做法。

There are plenty more bad practices in your code.

  • 不要扔了新的异常;定义你自己的异常类,并把它。这样调用者可以专门捕获你的异常。

  • Do not throw a new Exception; define your own exception class and throw it. That way the caller can catch your exception specifically.

不要抓住每一个异常,然后把它包在一个新的异常,并抛出。那点到底是什么?如果的每次的方法,这样做?很快你就会有一个例外包二十几级深,没有制定出什么异常的真正含义的能力。

Do not catch every exception and then wrap it in a new exception and throw that. What the heck is the point of that? What if every method did that? Soon you'd have an exception wrapped two dozen levels deep and no ability to work out what the exception really means.

不要抓住每一个异常,然后显示一个消息框。首先,这是合并的错误处理机制,code与用户界面code;把这两个分开的。其次,你可能会报告各种异常的位置 - 线程中止进出内存等等。钓的的具体的异常,并处理它; 如果你不知道如何从中恢复过来,不要吃它。

Do not catch every exception and then show a message box. First off, that is combining error handling mechanism code with user interface code; keep those two separate. Second, you are potentially reporting all kinds of exceptions here -- thread aborts and out of memory and whatever. Catch a specific exception and handle it; if you don't know how to recover from it, don't eat it.

这篇关于自从确定以返回异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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