Pattern to avoid nested try catch blocks?

后端 未结 16 508
無奈伤痛
無奈伤痛 2020-12-12 12:53

Consider a situation where I have three (or more) ways of performing a calculation, each of which can fail with an exception. In order to attempt each calculation until we f

16条回答
  •  有刺的猬
    2020-12-12 13:27

    using System;
    
    namespace Utility
    {
        /// 
        /// A helper class for try-catch-related functionality
        /// 
        public static class TryHelper
        {
            /// 
            /// Runs each function in sequence until one throws no exceptions;
            /// if every provided function fails, the exception thrown by
            /// the final one is left unhandled
            /// 
            public static void TryUntilSuccessful( params Action[] functions )
            {
                Exception exception = null;
    
                foreach( Action function in functions )
                {
                    try
                    {
                        function();
                        return;
                    }
                    catch( Exception e )
                    {
                        exception   = e;
                    }
                }
    
                throw exception;
            }
        }
    }
    

    And use it like so:

    using Utility;
    
    ...
    
    TryHelper.TryUntilSuccessful(
        () =>
        {
            /* some code */
        },
        () =>
        {
            /* more code */
        },
        calc1,
        calc2,
        calc3,
        () =>
        {
            throw NotImplementedException();
        },
        ...
    );
    

提交回复
热议问题