【问题标题】:How to remove try...catch block from many different functions [duplicate]如何从许多不同的功能中删除 try...catch 块[重复]
【发布时间】:2014-10-01 18:53:53
【问题描述】:

我有很多包含多个功能的类(WCF 服务)。现在我需要处理错误,但我不想在每个函数中创建一个块 try ... catch (用于错误处理)。

如何在任何类(或其他)中进行 try...catch,以便我们捕获错误但不在每个方法中写入相同的块?

【问题讨论】:

  • 我认为这不会有什么神奇的答案,但一些示例代码可以帮助我们了解确切的问题。
  • 如果您想要完全正确,使用任何可能引发异常的函数都需要尝试捕获,没有其他选择。
  • 所以您正在寻找通用异常捕获器?
  • 你为什么要捕捉错误?通常我们会尽量避免捕获错误,并让高级代码处理错误。
  • 我想你在找IErrorHandler

标签: c# try-catch


【解决方案1】:

总会有一些重复的代码,但你可以把它减少到一行

public static class ExceptionHandler
{
    public static void Run(Action action)
    {
        try
        {
           a();
        }
        catch(Exception e)
        {
           //Do Something with your exception here, like logging
        }
    }
}

然后打电话

ExceptionHandler.Run(yourAction);

您可以为函数添加重载,但这种方法并不理想。因为您可能希望在某些情况下捕获特定异常。

【讨论】:

    【解决方案2】:

    由于您没有具体提供代码,我将编写一些示例代码以使其更明显。如果你有这个:

    public class MyClass
    {
         public void Method1ThatCanThrowException() 
         {
              try 
              {
                  // the Method1 code that can throw exception
              }
              catch (MySpecificException ex) 
              {
                  // some specific error handling
              }
         }
    
         public object Method2ThatCanThrowException() 
         {
              try 
              {
                  // the Method2 code that can throw exception
              }
              catch (MySpecificException ex) 
              {
                  // the same specific error handling
              }
         }
    }
    

    因此,如果您打算进行单一位置错误处理,则可以使用 lambda,并借助私有方法:

    private T CheckAndCall<T>(Func<T> funcToCheck)
    {
         try 
         {
             return funcToCheck();
         }
         catch (MySpecificException ex) 
         {
             // the old specific error handling
         }
    }
    

    注意Func&lt;T&gt; 委托的使用。这是因为您可能需要将 try-catch 逻辑包装在一些可以返回值的代码周围。

    那么你可以像这样重写上面的方法:

    public void Method1ThatCanThrowException() 
    {
        CheckAndCall(
            () => 
            {
                // the Method1 code that can throw exception
                return null;
            });
    }
    
    public object Method2ThatCanThrowException() 
    {
        return CheckAndCall(
            () => 
            {
                // the Method2 code that can throw exception
                return someObject;
            });
    }
    

    【讨论】:

      【解决方案3】:

      例如,不必这样做:

      public class Program
      {
          public static string ReadFile(string filename)
          {
              //A BCL method that throws various exceptions
              return System.IO.File.ReadAllText(filename);
          }
      
          public static void Main(string[] args)
          {
              try
              {
                  Console.Write(ReadFile("name.txt"));
              }
              catch (Exception e)
              {
                  Console.WriteLine("An error occured when retrieving the name! {0}", e.Message);
              }
      
              try
              {
                  Console.Write(ReadFile("age.txt"));
              }
              catch (Exception e)
              {
                  Console.WriteLine("An error occured when retrieving the age! {0}", e.Message);
              }
          }
      }
      

      您可以根据需要使用refout 关键字来实现“Try...”方法:

      public class Program
      {
          public static bool TryReadFile(string filename, out string val)
          {
              try 
              {
                  val = System.IO.File.ReadAllText(filename);
                  return true;
              }
              catch (Exception)
              {
                  return false;
              }
          }
      
          public static void Main(string[] args)
          {
              string name, age;
      
              Console.WriteLine(TryReadFile("name.txt", out name) ? name : "An error occured when retrieving the name!");
      
              Console.WriteLine(TryReadFile("age.txt", out age) ? age: "An error occured when retrieving the age!");
          }
      }
      

      这种方法的缺点是您不能对特定异常采取行动,但在简单地确定操作是否成功的情况下,我发现这是一种语法上干净的方法。

      【讨论】:

        猜你喜欢
        • 2011-10-23
        • 1970-01-01
        • 2011-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多