我有一个看起来像这样的方法:
void throwException(string msg)
{
throw new MyException(msg);
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我写
int foo(int x, y)
{
if (y == 0)
throwException("Doh!");
else
return x/y;
}
Run Code Online (Sandbox Code Playgroud)
编译器会抱怨foo"并非所有路径都返回一个值".
是否有一个属性我可以添加到throwException以避免这种情况?就像是:
[NeverReturns]
void throwException(string msg)
{
throw new MyException(msg);
}
Run Code Online (Sandbox Code Playgroud)
我担心自定义属性不会这样做,因为为了我的目的,我需要编译器的合作.
我有一个像......的方法
int f() {
try {
int i = process();
return i;
} catch(Exception ex) {
ThrowSpecificFault(ex);
}
}
Run Code Online (Sandbox Code Playgroud)
这会产生编译器错误,"并非所有代码路径都返回值".但在我的情况下,ThrowSpecificFault()将始终抛出(相应的)异常.所以我被迫在最后放一个返回值,但这很难看.
首先,这种模式的目的是因为"process()"是对外部Web服务的调用,但需要转换各种不同的异常以匹配客户端的预期接口(我认为是〜外观模式).
有什么更干净的方法吗?
Reflector告诉我,SortedList使用ThrowHelper类来抛出异常而不是直接抛出它们,例如:
public TValue this[TKey key]
{
get
{
int index = this.IndexOfKey(key);
if (index >= 0)
return this.values[index];
ThrowHelper.ThrowKeyNotFoundException();
return default(TValue);
}
Run Code Online (Sandbox Code Playgroud)
其中ThrowKeyNotFoundException仅执行以下操作:
throw new KeyNotFoundException();
Run Code Online (Sandbox Code Playgroud)
注意这需要一个duff语句"return default(TValue)",它是无法访问的.我必须得出结论,这种模式的好处足以证明这一点.
这些好处是什么?