What is the best alternative “On Error Resume Next” for C#?

后端 未结 11 2796
南方客
南方客 2021-02-19 08:12

If I put empty catch blocks for my C# code, is it going to be an equivalent for VB.NET\'s \"On Error Resume Next\" statement.

try
{
    C# code;
}

catch(excepti         


        
11条回答
  •  太阳男子
    2021-02-19 08:43

    As been said by @Tim Medora, you have to make an effort to avoid using such approach when coding. However, in some cases it is useful, and it is possible to emulate such behavior. Here is a function and an example of using it. (Note that some code elements were written using C#6)

        /// 
        /// Execute each of the specified action, and if the action is failed, go and executes the next action.
        /// 
        /// The actions.
        public static void OnErrorResumeNext(params Action[] actions)
        {
            OnErrorResumeNext(actions: actions, returnExceptions: false);
        }
    
        /// 
        /// Execute each of the specified action, and if the action is failed go and executes the next action.
        /// 
        /// if set to true return list of exceptions that were thrown by the actions that were executed.
        /// if set to true and  is also true, put null value in the returned list of exceptions for each action that did not threw an exception.
        /// The actions.
        /// List of exceptions that were thrown when executing the actions.
        /// 
        /// If you set  to true, it is possible to get exception thrown when trying to add exception to the list. 
        /// Note that this exception is not handled!
        /// 
        public static Exception[] OnErrorResumeNext(bool returnExceptions = false, bool putNullWhenNoExceptionIsThrown = false, params Action[] actions)
        {
            var exceptions = returnExceptions ? new ArrayList() : null;
            foreach (var action in actions)
            {
                Exception exp = null;
                try { action.Invoke(); }
                catch (Exception ex) { if(returnExceptions) { exp = ex; } }
    
                if (exp != null || putNullWhenNoExceptionIsThrown) { exceptions.Add(exp); }
            }
            return (Exception[])(exceptions?.ToArray(typeof(Exception)));
        } 
    

    Example, instead of:

            var a = 19;
            var b = 0;
            var d = 0;
            try { a = a / b; } catch { }
            try { d = a + 5 / b; } catch { }
            try { d = (a + 5) / (b + 1); } catch { }
    

    you can:

                var a = 19;
                var b = 0;
                var d = 0;
                OnErrorResumeNext(
                    () =>{a = a / b;},
                    () =>{d = a + 5 / b;},
                    () =>{d = (a + 5) / (b + 1);}
                );
    

提交回复
热议问题