C # Error Code or Exception

I have a control circuit with which I communicate through a serial port. If the response command does not correspond to a specific format, I consider this an error, and I was wondering if I should return an error code or throw an exception? For instance:

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 (eg -99999) or thrown an exception? } else // Some unknown error occurred... { ... // Same question as above "if". } } else // Everything is OK, proceed as normal. ... } 

Thanks!

+6
source share
6 answers

In almost all cases, I could pass errors through exceptions. I would almost never use “error codes” as such - it is sometimes useful to give success / failure along with the result, as in int.TryParse , etc., but I don’t think that this situation works that way. This sounds like a real error condition that should stop further progress, although, therefore, an exception is appropriate.

EDIT: as noted in the comments, if the circuit reporting the error is really “expected”, and the caller should be able to deal with it and must actively look for this situation, then it is wise to use a status code.

Unfortunately, error handling is one of those things that we have not yet received in software development ...

+8
source

Strictly speaking, an exception will be used when you are in an “exceptional” circumstance, i.e. you do not expect.

If it were me, I would probably return an error code in the first case (known error response) and throw an exception in the second case (unknown error code)

+3
source

In your case, it is better to throw an exception. Because the calling method can distinguish between the "legitimate" output and the error condition. If you return the error code, it is still a numerical value, so the caller may incorrectly interpret it as exiting the control circuit.

+2
source

Personally, I like to deal with this situation by defining some kind of response object. I came to this through the experience of this and weighing what should be considered exceptional. If you interact with any device and the user turns off the device or something like that, this is an exceptional condition, and you should throw an exception.

If calling a specific method on a device fails or something else, this is not exceptional, but it is an error. I do not want to determine the magic number if I return a double, and I do not want to throw an exception. So, I define something like:

 class DeviceResult //could also be struct { public double ReturnValue { get; set; } public bool IsValid { get; set; } public string ErrorMessage { get; set; } } 

The features here are not very important - you adapt them to what the clients of your method want. In this example, the client API must verify that it is correct and, if so, use the return value - there is no magic number and no exception. The paradigm is important. The way I see it, you are using an object-oriented language so you can use objects. :)

+2
source

Error code.

  • Throwing exceptions is slower than returning values.
  • You can create a method signature so that you can return whatever type you want. If you needed to return a specific type that could not be extended in a meaningful way, you would definitely have to throw an exception.
  • When calling a method, it is easier to ignore exceptions than error codes. You will have to document the exceptions that your method throws, and hope that another developer reads it.
  • The response of the GetSensorValue method has different paths. The "happy journey" is obviously the expected and most interesting. But if you know that consumers can cope with the results of less crazy ways, then it makes sense to go with an error code, since the expected answer "unlucky path" is more expected.
  • Throwing a large number of exceptions can cause your debuger to constantly break depending on the debugger exception settings.
  • The returned error codes will definitely make your answer type more complex, which will require more code to expand the value. But is it really difficult to read and write "if (response.Status == Statuses.Success) {var value = response.Value;}" instead of try-catch?

If good practice is to make exceptions:

  • If you can anticipate that your method call will fail (check if you can complete the operation before it is executed). The execute method can be implemented to return an error code, but this pair of validation methods runs as a template.
  • You cannot extend the type of response in a meaningful way, but you need to signal the response in a state that was not provided for by the method contract.
  • As in the previous one, you have good reasons for returning only the result of a “happy journey”.
0
source

I would recommend using exceptions in most cases due to a few simple facts:

  • Exceptions are global, all C # developers know what an exception is (and hopefully) how to use it for debugging.
  • Exceptions are thrown from all call methods to the nearest try catch. If I have several layers and the innermost layer throws an exception, I can handle this exception in any layer that I need (usually the outermost or second outermost layer).
  • Most project types have some kind of redefinable method or event that can be overridden / signed to implement simple global exception handling code. This simplifies the formatting of error messages, logs, sends letters and prays to the gods (or what you guys do when you handle exceptions;)).

There are several things to consider:

  • You cannot throw an exception. If your code should be 100% optimized, then throwing exceptions might be what you want to avoid.
  • In exceptions, there is a lot of information that you might not need. Do you really need stacktrace if all you want to do is show the user a simple error message?

But as a rule, I would say: stick to the Exceptions, it is simple, informative, debugged and easy to use, although it can bring little performance

0
source

Source: https://habr.com/ru/post/899070/


All Articles