如何避免异常捕获.NET中的复制粘贴

使用.NET框架我有一个带有一组方法的服务,这些方法可以生成几种类型的异常:MyException2,MyExc1,Exception …为了为所有方法提供适当的工作,每个方法都包含以下部分:
[WebMethod]
void Method1(...)
{
    try
    {
        ... required functionality
    }
    catch(MyException2 exc)
    {
        ... process exception of MyException2 type
    }
    catch(MyExc1 exc)
    {
        ... process exception of MyExc1 type
    }
    catch(Exception exc)
    {
        ... process exception of Exception type
    }
    ... process and return result if necessary
}

在EACH服务方法中具有完全相同的东西(每个方法具有不同的参数集)与处理功能完全相同的异常是非常无聊的…

有没有可能“分组”这些捕获部分并只使用一行(类似于C宏)?可能.NET 4.0中的新内容与此主题有关吗?

谢谢.

附:欢迎任何想法.

解决方法

如果异常处理在所有方法中完全相同,您可以执行以下操作:
void CallService(Action method)
{
    try
    {
        // Execute method
        method();
    }
    catch(MyException2 exc)
    {
        ... process exception of MyException2 type
    }
    catch(MyExc1 exc)
    {   
        ... process exception of MyExc1 type
    }
    catch(Exception exc)
    {
        ... process exception of Exception type
    }
}

然后,您可以重写您的客户端代码

int i = 3;
string arg = "Foo";
this.CallService( () => this.Method1(i) );
this.CallService( () => this.Method2(arg,5) );

这允许您的Method1和Method2方法简单:

void Method1(int arg)
{
    // Leave out exception handling here...
    ... required functionality  
    ... process and return result if necessary
}

void Method2(string stringArg,int intArg)
{
    // Leave out exception handling here...
    ... required functionality  
    ... process and return result if necessary
}

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...