2010-12-09 59 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! 
}