I'm not a fan of the TrySomething
with out parameter pattern, so I would sooner do the following:
while (true) {
try {
possiblyFailingOperation();
break;
}
catch (Exception e) {
reportError();
if (abortRequested())
throw;
}
}
A TrySomething
function makes sense when there's several places that call the same exception-throwing function and they all want to immediately catch and handle a single kind of exception said function may throw. For example, TryParse
often makes sense as parsing may be common and may have only one failure state (no parse). It makes sense to do
if (!TryParse(x, out i))
i = default_value;
When there's only one function that calls the TrySomething
function, the added benefit is significantly less; we end up obscuring what exception is thrown and losing the ability to rethrow if necessary.
If this is all insignificant, a try function may be worthwhile; however, I'd use it in reaction to a common pattern, not in anticipation of one.