Catch multiple exceptions at once?

前端 未结 27 2535
夕颜
夕颜 2020-11-22 11:31

It is discouraged to simply catch System.Exception. Instead, only the "known" exceptions should be caught.

Now, this sometimes leads to unnecce

27条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 12:09

    I want to suggest shortest answer (one more functional style):

            Catch(() =>
                {
                    WebId = new Guid(queryString["web"]);
                },
                exception =>
                {
                    WebId = Guid.Empty;
                });
    

    For this you need to create several "Catch" method overloads, similar to System.Action:

        [DebuggerNonUserCode]
        public static void Catch(Action tryBlock,
            Action catchBlock)
        {
            CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2));
        }
    
        [DebuggerNonUserCode]
        public static void Catch(Action tryBlock,
            Action catchBlock)
        {
            CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2), typeof(TException3));
        }
    

    and so on as many as you wish. But you need to do it once and you can use it in all your projects (or, if you created a nuget package we could use it too).

    And CatchMany implementation:

        [DebuggerNonUserCode]
        public static void CatchMany(Action tryBlock, Action catchBlock,
            params Type[] exceptionTypes)
        {
            try
            {
                tryBlock();
            }
            catch (Exception exception)
            {
                if (exceptionTypes.Contains(exception.GetType())) catchBlock(exception);
                else throw;
            }
        }
    

    p.s. I haven't put null checks for code simplicity, consider to add parameter validations.

    p.s.2 If you want to return a value from the catch, it's necessary to do same Catch methods, but with returns and Func instead of Action in parameters.

提交回复
热议问题