一个CLASS的所有异常的异常处理程序 [英] One Exception handler for all exceptions of a CLASS

查看:93
本文介绍了一个CLASS的所有异常的异常处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有许多方法的类,并且希望为所有这些方法提供一个异常处理程序。
这些方法太多了,而且它们具有不同的参数,因此为每个方法编写try / catch很难看。

I have a class with number of methods and want to have one exception handler for them all. There are so many of these methods and they have different parameters, that it would be ugly to write try/catch for each of them.

知道我可以通过拥有一个类内异常处理程序来做到这一点的方法,它将处理所有这些操作。

Do you maybe know a way where I can do it with having a one in class exception handler, which will handle them all.

更新:

许多人问我为什么。原因是我正在使用各种方法调用数据源。
,所以我的班级有函数getData1,gedData2,getData3,getData4,....,getDataN。问题在于无法检查连接是否仍处于打开状态,并且创建新连接非常昂贵。因此,我尝试重用连接,并且如果下一个呼叫的连接失败,我将捕获该错误并重新连接,然后重试。这就是为什么我需要这个try / catch all block。

Many of you ask me why. The reason is that I am calling a data source with various methods. so my class has functions getData1, gedData2, getData3,getData4, ...., getDataN. The problem is that there is no way to check if the connection is still open and creating new connection is very very expensive. So I am trying to reuse connection and if the connection on the next call has failed, i would catch this and reconnect and try again. That is why i need this try/catch all block.

为此所有功能执行此操作:

to do this for all the functions:

try{    
   datasource.getData()
}
catch(ConnectionException)
{
   datasource.Connect();
   datasource.getData()
}






谢谢


Thanks

推荐答案

您可以使用委托将方法的代码传递到单个try catch中,如以下示例所示:

You could use a delegate to pass your method's code into a single try catch like the following example:

    private void GlobalTryCatch(Action action)
    {
        try
        {
            action.Invoke();
        }
        catch (ExpectedException1 e)
        {
            throw MyCustomException("Something bad happened", e);
        }
        catch (ExpectedException2 e)
        {
            throw MyCustomException("Something really bad happened", e);
        }
    }

    public void DoSomething()
    {
        GlobalTryCatch(() =>
        {
            // Method code goes here
        });
    }

这篇关于一个CLASS的所有异常的异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆