I have been studying this subject quite a bit, and I am unsure of what's the best way. I still have a lot to go trough (books, blogs, stack exchange, etc), but I simply can't find a consensus.
Basically here is the situation: You have a function that is expected to return a result, but the function fails (parameter is bad, exception occurs, resource is blocked / unreachable, etc), should you throw an exception or return something?
I simply don't see a best way of doing this, here is how things look:
People seem to agree that returning null and coding for null (expecting null and checking for it) is bad practice and I wholeheartedly agree. But on the other side of things people don't seem to like "vexing exceptions", for example Int32.parseInt
throws an exception instead of returning null, this function has a counterpart that does not do that (tryParse) which returns a boolean but has an output parameter:
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
I personally find this method a bit vexing, I studied threading under linux and most methods were methodA(in, in, out, in)
which is horrible. With a proper IDE this issue is way smaller, but it still left a bad taste in my mouth.
And in some languages (like Java) this is not exactly easy to do, since it has no out
descriptor (or whatever it's called) and it passes by value.
So it comes down to this: How would this be better handled? Add exceptions to when your code can't complete (if it isn't a number, I can't parse it, I can't return a number), or should you work around the issue. In C, C++, or C# I would probably always go with the bool method(in, out)
approach, but in Java this seems like a really painful way of solving the issue, and I'm not sure if it's available in other languages or not.