I’ve read in The Pragmatic Programmer, and in some other articles (including one from Joel Spolsky), that you should only throw Exceptions in exceptional cases. Otherwise, you should return an error.
Sometimes it is possible (returning -1, -0, or a positive number, for example), but there are other cases where that is not possible. I mean, if you are returning a class, you can always return null, but I think the idea is to return something that will alert the caller what happened.
If I always return null, I don’t think it is useful to say: If this method returns null, it could be because of A, B, C, D, or E
So, how exactly can this be implemented in C#?
Edit:
Hours after I posted this question, I saw another question here where the question itself was about wheter the code posted in was a good practice or not.
I see that is another way of doing what I was asking here. Here is the link:
By using numbers you’re directly contradicting what Microsoft recommend with Exceptions. The best source of information I’ve found that de-mystifies the whole subject, is Jeffrey Richter’s CLR via C# 3. Also the .NET Framework Guidelines book is worth a read for its material on Exceptions.
To quote MSDN:
One solution you could adopt is an
outparameter, which gets the result. Your method then returns aboolmuch like a lotTryParsemethods you meet in the framework.