我想在C#中做這樣的事情。我認爲這可以使用委託或匿名方法。我試過但我做不到。需要幫忙。使用try catch將值賦給C#var
SomeType someVariable = try {
return getVariableOfSomeType();
} catch { Throw new exception(); }
我想在C#中做這樣的事情。我認爲這可以使用委託或匿名方法。我試過但我做不到。需要幫忙。使用try catch將值賦給C#var
SomeType someVariable = try {
return getVariableOfSomeType();
} catch { Throw new exception(); }
您可以創建一個通用的輔助功能:
static T TryCatch<T, E>(Func<T> func, Func<E, T> exception)
where E : Exception {
try {
return func();
} catch (E ex) {
return exception(ex);
}
}
,你可以調用像這樣:
static int Main() {
int zero = 0;
return TryCatch<int, DivideByZeroException>(() => 1/zero, ex => 0);
}
此評估1/zero
TryCatch
的try
的範圍內,從而導致異常處理程序進行評估,其簡單地返回0
我懷疑這將比直接在Main
中的幫助變量和try
/catch
語句更具可讀性,但如果您遇到這種情況,則可以這樣做。
而不是ex => 0
,你也可以讓異常函數拋出別的東西。
你應該做這樣的事情:
SomeType someVariable;
try {
someVariable = getVariableOfSomeType();
}
catch {
throw new Exception();
}
SomeType someVariable = null;
try
{
someVariable = GetVariableOfSomeType();
}
catch(Exception e)
{
// Do something with exception
throw;
}
你可以試試這個
try
{
SomeType someVariable = return getVariableOfSomeType();
}
catch { throw; }
SomeType someVariable = null;
try
{
//try something, if fails it move to catch exception
}
catch(Exception e)
{
// Do something with exception
throw;
}
這對我有意義。像往常一樣評估一個表達式,除了如果表達式的評估結果是一個異常,那麼這個異常就會被捕獲。 C#'try'語句只能包含語句,並且不能返回值。 – hvd
@hvd:謝謝! 從來沒有想過: - 「try語句只能包含語句,並且不能返回值」 – rak
@geedubb: 如果你精心解釋了爲什麼代碼或問題沒有意義,可能會有幫助。 – rak