用单个全局try catch块替换多个try catch

时间:2019-12-09 17:12:23

标签: c# exception error-handling

我试图针对全局try catch异常处理程序,因为我有几个子类 有尝试的方法会陷入其中。所以基本上我希望父类方法能够捕获所有这些 例外并记录下来。

常见的一种是SQL异常。

这里创建可捕获错误的通用处理程序的最佳方法是什么?

这是我的应用程序中发生的事的一个示例

public class Parent
{
    public void ParentMethod()
    {
        try
        {
            var childClass = new Child();
            var process = childClass.Process();
            if (process)
            {
                // Do this
            }
            else
            {
                // raise new Exception
            }
        }
        catch(Exception ex){
            WriteToErrorLogger.Error(ex)
        }       
    }
}
public class Child
{
    public bool Process()
    {
        try{
            // Do something and save to Database
        }
        catch (SqlException sqlEx)
        {
            // log exception
            return false;
        }
        catch (Exception ex)
        {
            // log exception
            return false;
        }       
    }
}

1 个答案:

答案 0 :(得分:1)

什么意思?有意义的是做相反的事情

public class Parent
{
    public void ParentMethod()
    {
        try
        {
            var childClass = new Child();
            var process = childClass.Process();
            if (process)
            {
                // Do this
            }
            else
            {
                // raise new Exception
            }
        }
        catch (SqlException sqlEx)
        {
            WriteToErrorLogger.Error(ex);
        }
        catch(Exception ex){
            WriteToErrorLogger.Error(ex);
        }       
    }
}

孩子

public class Child
{
    public bool Process()
    {
            // Do something and save to Database       
    }
}

如果您想有条件地这样做,可以像这样改变孩子

public class Child
{
    public bool Process(bool rethrow = false)
    {
        try{
            // Do something and save to Database
        }
        catch (SqlException sqlEx)
        {
            if(rethrow) throw;
            // log exception
            return false;
        }
        catch (Exception ex)
        {
            if(rethrow) throw
            // log exception
            return false;
        }       
    }
}