Answer the question
In order to leave comments, you need to log in
What is the best way to return a result from a function if there is no guarantee that it will complete correctly?
It happens that a function cannot always produce a result, because either the parameters are not correct, or an exception will be thrown, or the operation will be canceled from outside.
Is there a better way to display the result?
* Place a function in a class, and create fields in the class to signal each nuance that has happened.
* Declare a structure as the output type of the function, where the fields will be responsible for every possible nuance. And work with the returned result like this:
if(result.IsCorrect && result.value)
x = result.value
else if (result.canceled)
…
* Feel free to write a function, and if something goes wrong, throw exceptions.
* Use events.
* Use monads.
Or, as always, does the choice of solution depend on the specific problem being solved?
Answer the question
In order to leave comments, you need to log in
The choice depends on the task.
Here's another option for you. Return the instance of the exception, or null if there is no error, and the value via the out parameter.
The function returns bool - whether it was successful or not. And the result is in the output parameter.
Following the example of TryParse
var result = 0;
try
{
result = magic();
}
catch
{
/*....*/
}
finaly
{
return result;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question