2010-12-09 61 views
7

在我的對象轉換的代碼,我有一大堆:如何在處理C#中的異常時壓縮大量小的Try-Catch塊?

try 
    { 
     NativeObject.Property1= int.Parse(TextObject.Property1); 
    } 
    catch (Exception e) 
    { 
     Trace.WriteLineIf(ConverterSwitch.TraceVerbose, e); 
    } 
    try 
    { 
     NativeObject.Property2= DateTime.Parse(TextObject.Property2); 
    } 
    catch (Exception e) 
    { 
     Trace.WriteLineIf(ConverterSwitch.TraceVerbose, e); 
    } 

等等......我不希望所有轉換失敗的某些屬性的原因,所以我不能把這一切都在一個try塊,但我需要登錄,如果有什麼失敗,並繼續..
有沒有辦法來壓縮所有這些嘗試抓住的東西?

可惜我們不能像C#代碼寫:

try 
{ 
    int num = int.Parse("3"); 
    decimal num2 = decimal.Parse("3.4"); 
} 
catch (Exception e) 
{ 
    Trace.Write(e); 
    continue; //continue execution from the point we left. (line 2) 
} 
+2

如果切換到VB.NET,你可以使用'上的錯誤恢復Next` :-) – 2010-12-09 16:27:45

+1

某處VB6/VBA開發者在你的竊笑。從來沒有想過我會聽到有人鬆「因爲錯誤恢復下一個」 – JohnFx 2010-12-09 16:28:24

+2

@Cody:哦,上帝​​。哦,上帝不。請不。 – cdhowie 2010-12-09 16:29:15

回答

8

沒有,但您可以:

private static void ExecuteAndCatchException(Action action) 
{ 
    try 
    { 
    action(); 
    } 
    catch (Exception e) 
    { 
    Trace.Write(e); 
    } 
} 

然後

ExecuteAndCatchException(() => NativeObject.Property1 = int.Parse(TextObject.Property1)); 
ExecuteAndCatchException(() => NativeObject.Property2 = DateTime.Parse(TextObject.Property2)); 
3

你可以做這樣的事情:

private static void Attempt(Action action) 
{ 
    try { action(); } 
    catch (Exception e) { 
     Trace.WriteLineIf(ConverterSwitch.TraceVerbose, e); 
    } 
} 

然後:

Attempt(() => NativeObject.Property1 = int.Parse(TextObject.Property1)); 
Attempt(() => NativeObject.Property2 = DateTime.Parse(TextObject.Property2)); 
1

這聽起來像你正在尋找一個類似於VBs的On Error + Resume Next。 C#沒有這樣的設施。我能想到的最好的壓縮方法是使用lambda表達式和輔助方法。

private void Wrap(Action del) { 
    try { 
    del(); 
    } catch (Exception e) { 
    Trace.WriteLineIf(ConverterSwitch.TraceVerbose, e); 
    } 
} 

Wrap(() => { NativeObject.Property1= int.Parse(TextObject.Property1); }); 
Wrap(() => { NativeObject.Property2= DateTime.Parse(TextObject.Property2); }); 
12

可以使用TryParse方法。請參閱下面的示例代碼來分析Int32值。

private static void TryToParse(string value) 
    { 
     int number; 
     bool result = Int32.TryParse(value, out number); 
     if (result) 
     { 
     Console.WriteLine("Converted '{0}' to {1}.", value, number);   
     } 
     else 
     { 
     if (value == null) value = ""; 
     Console.WriteLine("Attempted conversion of '{0}' failed.", value); 
     } 
    } 
0

你可以寫一個封裝轉換和記錄作爲這樣一個SafeConvert類:

public static class SafeConvert{ 

    public static int ParseInt(string val) 
    { 
    int retval = default; 
    try 
    { 
     retval = int.Parse(val); 
    } 
    catch (Exception e) 
    { 
     Trace.WriteLineIf(ConverterSwitch.TraceVerbose, e); 
    } 
     return retval; 
} 

}

0

雖然我不知道有關異常塊縮短,我喜歡這個主意你已經提出。這與舊版VB中的On Error Resume Next類似。當執行Parse-ing負載時,我會在可用時使用TryParse的路線。然後,你可以這樣說:

If(!DateTime.TryParse(TextObject.Property2, out NativeObject.Property2)) { 
    // Failed! 
}