У меня есть методы для чтения различных датчиков и обработки данных. В рамках этих методов у меня есть другие методы, которые отправляют команды в цепь через последовательный порт (чтобы получить значения датчика). Может произойти ошибка связи, и мне было интересно, можно ли когда-нибудь "вернуть" исключение? Например:
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.
}
Это когда-нибудь нормально или считается "плохой практикой"?
Спасибо!
EDIT
Хорошо, я перечитал различные ответы, и похоже, что я делаю это совершенно неправильно (голый со мной, я - мех. Англ.). Я попытался использовать вышеизложенное в качестве быстрого примера, но похоже, что я должен был просто опубликовать полную информацию с самого начала. Итак, вот более подробный пример моей ситуации:
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().
Вот моя логика, если ...
Порядок вызовов: GetHeightAtCoords () -> MoveToCoords () -> GetCurrentCoords () -> GetXEncoderValue (), ошибка с ответом контроллера.
Создать новое исключение в GetXEncoder (), перехватить в GetCurrentCoords () и повторно выдать новое исключение, перехватить в MoveToCoords () и повторно выбросить новое исключение, поймать в GetHeightAtCoords () и отобразить сообщение в строке состояния (message = " Ошибка в GetHeightAtCoords (): Ошибка в MoveToCoords (): Ошибка в GetCurrentCoords (): Чтение значения X Ошибка-6: Ошибка состояния ").
Поскольку GetXEncoder () может вызываться из нескольких мест внутри метода, я решил, что если я позволю исходному исключению всплыть до конца, это будет мало чем помочь пользователю (например, «Ошибка в GetHeightAtCoords (): чтение» Ошибка значения X-6: ошибка состояния ", в какое время?). Возьмите этот пример, какое значение Read X Value не удалось? GetHeightAtCoords () -> MoveToCoords () -> GetCurrentCoords () -> GetXEncoderValue () ИЛИ GetHeightAtCoords () -> GetCurrentCoords () -> GetXEncoderValue ()?
Надеюсь, это более понятно: /
Что-нибудь подобное когда-нибудь было сделано? Как бы вы посоветовали мне продолжить? Еще раз спасибо всем за ваш вклад!