在处理C#中的异常时,如何压缩大量的小型Try-Catch块?

Ale*_*sev 7 .net c# exception-handling exception 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);
    }
Run Code Online (Sandbox Code Playgroud)

等等...我不希望所有转换都失败导致某些属性因此我不能将所有这些放在一个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)
}
Run Code Online (Sandbox Code Playgroud)

Bob*_*ack 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);
      }
   }
Run Code Online (Sandbox Code Playgroud)

  • 是的,这是正确的方法,假设问题中的示例代码准确地描述了您想要使用这些嵌套的 Try-Catch 块完成的任务的范围。尽可能“预防”异常总是比尝试处理异常更好。 (2认同)

vc *_* 74 9

不,但你可以:

private static void ExecuteAndCatchException(Action action)
{
  try 
  { 
    action();
  } 
  catch (Exception e) 
  { 
    Trace.Write(e); 
  } 
}
Run Code Online (Sandbox Code Playgroud)

然后

ExecuteAndCatchException(() => NativeObject.Property1 = int.Parse(TextObject.Property1)); 
ExecuteAndCatchException(() => NativeObject.Property2 = DateTime.Parse(TextObject.Property2));
Run Code Online (Sandbox Code Playgroud)