C#是否该支持“try/catch/else”语法

以前用过一段时间Python,里面有个try/catch/else语法,我觉得挺好用,这个语法形如下:

try:
    print('try...')
    r = 10 / int('2')
    print('result:', r)
except ValueError as e:
    print('ValueError:', e)
except ZeroDivisionError as e:
    print('ZeroDivisionError:', e)
else:
    print('no error!')
finally:
    print('finally...')
print('END')

这段代码来至廖雪峰的教程,我觉得这个语法挺好的,我举一个C#的例子:

static void Main(string[] args)
{
    int result = 0;
    bool hasEx = false;

    try
    {
        result = Div(100, 1);
    }
    catch (Exception ex)
    {
        Console.WriteLine("it's wrong:" + ex.Message);
        hasEx = true;
    }
    if (!hasEx)
    {
        DoSomthing(result);
    }

    Console.ReadLine();
}

static int Div(int dividend, int divider)
{
    return dividend / divider;
}

static void DoSomething(int result)
{
    Console.WriteLine("do somthing with " + result);
}

上例中,我想在调用Div方法没有抛出异常的情况下才执行DoSomething方法,一般的处理方法如上面代码所示,用一个bool型变量来判断是否超出了异常,这样写出的代码并不是很优雅。也许有人会说把DoSomething方法放到Div方法的下面,如果Div方法抛出了异常的话就不会执行DoSomething方法了,但是这样做有一个问题:一个try块中放置多个可能抛出异常的方法本身不太合理,一旦catch到异常,可能需要额外的设计才能使得catch中的代码知道异常到底是Div方法抛出的还是DoSomething抛出的。基于如上考虑,我写了一个辅助类:

public static class TryCatchElseHelper
{
    public static void Do<TResult>(Func<TResult> tryToDo, 
        Action<Exception> catchTodo, 
        Action<TResult> elseTodo)
    {
        bool catchEx = false;
        TResult result = default(TResult);

        try
        {
            if (tryToDo != null)
            {
                result = tryToDo();
            }
        }
        catch (Exception ex)
        {
            catchEx = true;
            catchTodo?.Invoke(ex);
        }
        if (!catchEx)
        {
            elseTodo?.Invoke(result);
        }
    }
}

调用此类,上面Main函数里的代码可简化如下:

static void Main(string[] args)
{
    TryCatchElseHelper.Do<int>(() => Div(100, 0),
        ex => Console.WriteLine("it's wrong " + ex.Message),
        r => DoSomething(r));

    Console.ReadLine();
}

以上代码本属雕虫小技,大家可以借此来讨论讨论微软是否有必要在C#将来的版本中加入try/catch/else的语法,谢谢,祝节日愉快。

posted @ 2017-04-28 11:53  会长  阅读(1422)  评论(16编辑  收藏  举报