Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6699945
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T06:45:22+00:00 2026-05-26T06:45:22+00:00

I have methods to read various sensors and process data. Within these methods I

  • 0

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”?

Thanks!

EDIT

I read over the various responses and it looks like I am doing this completely wrong. 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…

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

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

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() ?

Hopefully that is more clear :/

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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T06:45:23+00:00Added an answer on May 26, 2026 at 6:45 am

    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)); 
    }
    

    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.

    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.

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

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In our various applications, we have a hodge-podge of different methods used to read
I have read about partial methods in the latest C# language specification , so
I have read this post about how to test private methods. I usually do
I have read an example and tried to duplicate it's methods but with weird
I have a C# database layer that with static read method that is called
I have methods with more than one parameter that are guarded against bad input
I have methods in all of my models that look like this: def formatted_start_date
In C# I have methods that use [WebMethod(EnableSession = true)] I consume them in
Some existing web services I consume have methods that look something like this: List<Employee>
I am testing various methods to read (possibly large, with very frequent reads) XML

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.