2013-11-20 51 views
-4

我想在C#中做這樣的事情。我認爲這可以使用委託或匿名方法。我試過但我做不到。需要幫忙。使用try catch將值賦給C#var

SomeType someVariable = try { 
          return getVariableOfSomeType(); 
         } catch { Throw new exception(); } 
+1

這對我有意義。像往常一樣評估一個表達式,除了如果表達式的評估結果是一個異常,那麼這個異常就會被捕獲。 C#'try'語句只能包含語句,並且不能返回值。 – hvd

+0

@hvd:謝謝! 從來沒有想過: - 「try語句只能包含語句,並且不能返回值」 – rak

+0

@geedubb: 如果你精心解釋了爲什麼代碼或問題沒有意義,可能會有幫助。 – rak

回答

1

您可以創建一個通用的輔助功能:

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/zeroTryCatchtry的範圍內,從而導致異常處理程序進行評估,其簡單地返回0

我懷疑這將比直接在Main中的幫助變量和try/catch語句更具可讀性,但如果您遇到這種情況,則可以這樣做。

而不是ex => 0,你也可以讓異常函數拋出別的東西。

+0

這更適合F#。 – Romoku

+0

我不是很熟悉F#,但是[看文檔](http://msdn.microsoft.com/en-us/library/vstudio/dd233194.aspx),看起來你是對的,F#已經在本地支持。很高興知道。 – hvd

+0

模式匹配是一件美麗的事情。 – Romoku

0

你應該做這樣的事情:

SomeType someVariable; 
try { 
    someVariable = getVariableOfSomeType(); 
} 
catch { 
    throw new Exception(); 
} 
0
SomeType someVariable = null; 

try 
{ 
    someVariable = GetVariableOfSomeType(); 
} 
catch(Exception e) 
{ 
    // Do something with exception 

    throw; 
} 
0

你可以試試這個

try 
{ 
    SomeType someVariable = return getVariableOfSomeType(); 
} 
catch { throw; } 
0
SomeType someVariable = null; 

try 
{ 
    //try something, if fails it move to catch exception 
} 
catch(Exception e) 
{ 
    // Do something with exception 

    throw; 
}