【发布时间】:2010-12-20 13:17:07
【问题描述】:
是否可以编写像outType? TryDo(func, out exception, params) 这样的方法,调用func(arg1,arg2,arg3,...),其中params 包含arg1,arg2,arg3,...,然后返回func 返回值,如果发生任何异常返回null 并设置异常?
这可以通过另一个函数签名更好地完成吗?
例如我有
string Foo1(int i) { return i.ToString()}
void Foo2(int[] a) {throw new Exception();}
然后调用
string t = TryDo(Foo1, out ex, {i});
TryDo(Foo2, out ex, {});
-----------已编辑-------
string t;
SomeClass c;
try
{
t = Foo1(4, 2, new OtherClass());
}
catch (Exception ex)
{
Log(ex);
if (/*ex has some features*/)
throw ex;
}
try
{
Foo2();
}
catch (Exception ex)
{
Log(ex);
if (/*ex has some features*/)
throw ex;
}
.
.
.
我想变成这样。
string t = TryDo(Foo1, out ex, {4, 2, new OtherClass());
Examine(ex);
SomeClass c = TryDo(Foo2, out ex, {});
Examine(ex);
【问题讨论】:
-
如果你的代码中有太多的 try/catch 块,你很可能做错了什么。您应该只捕获您可以实际处理的异常并让所有其他异常传播。
-
+1 @ Brian Rasmussen。另外,请注意,如果您从单个方法处理多个异常,则不必嵌套捕获。例如:
try { /* file i/o */ } catch (AccessDenied ex){} catch (FileNotFound ex){} catch (IOException ex){} // etc -
(如果你在做某种 I/O,如果健壮性很重要,你总是会有很多错误处理)
-
@brian:如果我确定应该传播异常,然后我再次抛出,不要试图通过删除它来回答问题。
-
@HPT:你能给我们举个例子说明问题中的“too many try-catch”是什么样的吗?