此问题是从How to indicate that a method was unsuccessful开始的后续操作。 xxx()Tryxxx()模式在许多库中非常有用。我想知道在不重复我的代码的情况下提供两种实现的最佳方式。“TryParse/Parse like”模式:实现它的最佳方式是什么
什么是最好的:
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太贵了?有没有办法在第二个例子中捕获异常?
只要您的TryX实现不需要捕获异常(即,您的代码生成的异常,而不是代码生成的异常),我会同意您的直觉(如果可能,请避免TryX病例的异常)你打电话)。 – 2008-10-08 12:28:06
此外,我不确定你的意思是“有没有办法在第二个例子中捕捉异常?” - 抓住什么异常?你想抛出DoSomething(尽管你会抛出一个特定的异常,而不是一般的异常)。 – 2008-10-08 12:28:52
@Jonathan:我的意思是“重新抛出发生在内部处理中的异常,调用者可以知道是什么导致了错误” – Luk 2008-10-08 12:31:08