This question is a follow-up from How to indicate that a method was unsuccessful. The xxx() Tryxxx() pattern is something that can be very useful in many libraries. I am wondering what is the best way to offer both implementations without duplicating my code.
What is best:
public int DoSomething(string a)
{
// might throw an exception
}
public bool TrySomething(string a, out result)
{
try
{
result = DoSomething(a)
return true;
}
catch (Exception)
{
return false;
}
or
public int DoSomething(string a)
{
int result;
if (TrySomething(a, out result))
{
return result;
}
else
{
throw Exception(); // which exception?
}
}
public bool TrySomething(string a, out result)
{
//...
}
I'd instinctively assume that the first example is more correct (you know exactly which exception happened), but couldn't the try/catch be too expensive? Is there a way to catch the exception in the second example?