具有相同 try/catch 逻辑的多种方法

Multiple methods with same try/catch logic

我有一个 C# 程序,其中包含多个方法,这些方法具有不同的参数和不同的 return 类型,但它们中的大多数都有一个具有相同异常逻辑处理的 try/catch 块。所有方法都有多个catch语句,但是里面的逻辑对所有方法都是一样的。

有没有办法创建一个辅助方法,这样我就不会在 catch 中有重复的代码?

    public static async Task<long> Method1(string requestedKey)
    {
        try
        {
            //code
            return value;
        }
        catch (Exception1 ex)
        {
            Exception1Handler(ex);
        }
        catch (Exception2 ex)
        {
            Exception2Handler(ex);
        }
        catch (Exception3 ex)
        {
            Exception3Handler(ex);
        }
        catch (Exception ex)
        {               
        }

        return 0;
    }


    public static async Task<T> Method2(string key, string value)
    {
        try
        {
            //code
            return value;
        }
        catch (Exception1 ex)
        {
            Exception1Handler(ex);
        }
        catch (Exception2 ex)
        {
            Exception2Handler(ex);
        }
        catch (Exception3 ex)
        {
            Exception3Handler(ex);
        }
        catch (Exception ex)
        {               
        }

         return default(T);
    }

如何将 catch 语句分组到辅助方法中,以免出现重复代码?

如果想避免重复 catch 块,可以使用以下方法

public void HandleException(Action action)
{
    try
    {
        action();
    }
    catch (Exception1 e)
    {
        // Exception1 handling
    }
    catch (Exception2 e)
    {
        // Exception2 handling
    }
    catch (Exception3 e)
    {
        // Exception3 handling
    }
    catch (Exception e)
    {
        // Exception handling
    }
}

...

HandleException(() => /* implementation */)

而不是这个 :

void AA(string B)
{
    try
    {
        //Do something
    }
    catch (Exception)
    {
        //Do something else
    }
}

void AA(string B, string C)
{
    try
    {
        //Do something
    }
    catch (Exception)
    {
        //Do something else
    }
}

并一遍又一遍地输入相同的异常(我假设它们将完全相同,因为你在你的问题中是这样说的) 你可以这样做:

void CallerMethod()
{
    try
    {
        AA("");
        AA("", "");
    }
    catch (Exception)
    {
        //My only one exception
    }
}

void AA(string B)
{
    //Do something
}

void AA(string B, string C)
{
    //Do something
}

这样,如果您的任何重载方法将抛出异常,您只能从一个地方处理它们