• 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的语法,谢谢,祝节日愉快。

  • 相关阅读:
    数据结构_线性结构
    多线程01_基础
    操作系统05_文件管理
    解析静态内部类的使用目的与限制(转)
    mysql去除重复记录案例
    mysql 索引使用策略及优化
    mysql 索引数据结构及原理
    mysql 索引的简单使用
    当一个线程进入一个对象的一个synchronized方法后,其它线程是否可进入此对象的其它方法
    14 线程间协作的两种方式:wait、notify、notifyAll和Condition
  • 原文地址:https://www.cnblogs.com/zzy0471/p/trycatchelse.html
Copyright © 2020-2023  润新知