投擲Exception
類是不好的做法以及沒有重新投擲追趕Exception
通過throw;
(請注意語法):
// Whatever happened (e.g. CPU starts emittinig green smoke)
} catch (Exception ex) {
// throw Exception instance which means nothing more than "Something went wrong"
ex.ThrowNew("Failed to return Bar");
}
首先,讓我們修改初始代碼:
try {
...
}
// We do know the cause, that's why we have a right to catch and re-throw
catch (DivideByZeroException e) {
// Be specific, do not throw Exception! Since MyBarException can be caought in "catch"
throw new MyBarException("Failed to return Bar because...", e);
}
,如果你想在這裏的任何擴展方法,我懷疑,但是如果你堅持,你應該把類似
// Doesn't compile; to show the idea only
public static void ThrowNew<T>(this Exception ex, string message)
where T: Exception {
if (null == ex)
return; // or throw ArgumentNullException("ex");
throw new T(message, ex); // <- this line fails to compile
}
上面的代碼已經與new T
問題(.NET不能確保任意T
有構造 要求),所以你必須添加反射爲
public static void ThrowNew<T>(this Exception ex, string message)
where T: Exception {
if (null == ex)
return; // or throw ArgumentNullException("ex");
throw (Exception) (typeof(T)
.GetConstructor(new Type[] { typeof(String), typeof(Exception)})
.Invoke(message, ex));
}
所以你可以把
catch (DivideByZeroException e) {
e.ThrowNew<MyBarException>("Failed to return Bar because...");
// Ugly little thing:
// "if (null == ex)" in the extension method doesn't throw any exception
return false;
}
其是,IMHO,少可讀,因此不應該被用於
的方法不編譯 - 「不是所有的代碼路徑返回一個值」。你的意思是「不起作用」? –
你能澄清究竟發生了什麼嗎?它拋出什麼錯誤?據我所知,這應該工作(並拋出'失敗返回酒吧') – FrankerZ
當你說這是行不通的,你的意思是? –