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

标签 c# .net exception exception-handling 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 block 中,但如果某些事情失败我需要记录并继续..
有没有办法压缩所有这些 try catch 东西?

遗憾的是我们不能用 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)
}

最佳答案

如果可用,您可以使用 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);
      }
   }

关于c# - 在 C# 中处理异常时,如何压缩大量小的 Try-Catch block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4400533/

相关文章:

c# - WPF ProgressBar 在更新太快时会失去光泽 - 错误?

c++ 异常:抛出 std::string

exception - 资源注释 : No qualifying bean of type [javax. sql.DataSource] 已定义:预期单个匹配 bean 但找到 2

c# - 从 .NET Core XUnit 项目引用标准 dll

c# - String 和 Char 类型如何存储在 .NET 的内存中?

c# - 正则表达式仅用于数字加上 'h' 字符

c# - 如何正确读取 Interlocked.Increment'ed int 字段?

.net - 登录部署到 Azure 的 .Net 的首选方式

c# - SqlConnection 问题,ASP.net C#

.net - 在运行时获取 OutofMemoryException 消息 "Insufficient memory to continue the execution of the program"