Sometimes you just need to know whether an operation succeeded or not.
The most straightforward example that I can think of is the TryParse metaphor in the .NET Framework. TryParse exists for a number of reasons:
- You can control the lifetime of the variable you're putting the parse result into,
- Exceptions are too expensive to be throwing if you're in the middle of a long loop, and
- A success flag allows an appropriate value to be substituted for a failed parse (like zero, perhaps).
TryParse looks like this:
bool result SomeNumericType.TryParse(string text, out SomeNumericType value)
Let's say you're trying to parse some numeric columns in a large text file as quickly as possible, but one of the columns contains a text character. If you use a Parse method that throws exceptions, you've just crippled your parser.
On the other hand, if you do something like this:
public double ParseColumn(string text)
double number= 0;
if (double.TryParse(text), out number)
// optionally analyze text for the reasons why, log the problem, or whatever
Then you've avoided having to trap the dreaded exception, an operation that is typically three orders of magnitude slower than returning an error code or success result, and you've lowered the overhead as much as humanly possible for the general case (a successful parse operation).