この質問は、メソッドが失敗したことを示す方法からのフォローアップです。xxx()Tryxxx()パターンは、多くのライブラリで非常に役立つものです。コードを複製せずに両方の実装を提供するための最良の方法は何でしょうか。
最高のもの:
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;
}
また
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)
{
//...
}
私は本能的に最初の例がより正しいと思います(どの例外が発生したかを正確に知っています)が、try / catchは高すぎるのではないでしょうか?2番目の例で例外をキャッチする方法はありますか?