Ignore Exception in C#

后端 未结 9 732
梦毁少年i
梦毁少年i 2020-11-29 11:15

Is there a better way to ignore an exception in C# than putting it up in a try catch block and doing nothing in catch? I find this syntax to be cumbersome. For a codeblock,

相关标签:
9条回答
  • 2020-11-29 11:28

    No. When exceptios occur, they travel back up the call stack either until they are handled by a catch block or the entire process terminates.

    0 讨论(0)
  • 2020-11-29 11:31

    I don't think there is a trick to avoid exception but you can use the following code snippet:

    public void IgnoreExceptions(Action act)
    {
       try
       {
          act.Invoke();
       }
       catch { }
    }
    

    Using the method looks like:

    IgnoreExceptions(() => foo());
    

    Another solution is to use AOP (Aspect Oriented Programming) - there's a tool called PostSharp which enables you to create an attribute that would catch all exceptions in specific assembly/class/method, which is closer to what you're looking for.

    0 讨论(0)
  • 2020-11-29 11:31
        public static void Ignore<T>(Action a) where T : Exception
        {
            try
            {
                a();
            }
            catch (T)
            {
            }
        }
    

    To use:

        Ignore<InvalidOperationException>(() => foo());
    
    0 讨论(0)
  • 2020-11-29 11:32

    No. If an exception is thrown, it is usually a critical error which has happend. You do not want to ignore it.

    Instead you should rewrite your code to check for the errors and only if it really fails, a exception is cast.

    For example using Int32.TryParse instead of Int32.Parse to check if an object is an valid integer. Remember that exceptions are very expensive when they are cast and many casts severely affect performance of your application.

    0 讨论(0)
  • 2020-11-29 11:36

    I wanted to contribute the extension methods I created based on previous answers. Hope it helps someone.

    /// <summary>
    /// Extension methods for <see cref="Action"/> objects.
    /// </summary>
    public static class ActionExtensions
    {
        /// <summary>
        /// Executes the <paramref name="action"/> and ignores any exceptions.
        /// </summary>
        /// <remarks>
        /// This should be used in very rare cases.
        /// </remarks>
        /// <param name="action">The action to execute.</param>
        public static void IgnoreExceptions(this Action action)
        {
            try { action(); }
            catch { }
        }
    
        /// <summary>
        /// Extends an existing <see cref="Action"/> so that it will ignore exceptions when executed.
        /// </summary>
        /// <param name="action">The action to extend.</param>
        /// <returns>A new Action that will ignore exceptions when executed.</returns>
        public static Action AddIgnoreExceptions(this Action action)
        {
            return () => action.IgnoreExceptions();
        }
    }
    

    And the unit tests:

    [TestClass]
    public class ActionExtensionsTests
    {
        [TestMethod]
        public void IgnoreException()
        {
            Action justThrow = () => { throw new InvalidOperationException(); };
            justThrow.IgnoreExceptions();
        }
        [TestMethod]
        public void AddIgnoreException()
        {
            Action justThrow = () => { throw new InvalidOperationException(); };
            var newAction = justThrow.AddIgnoreExceptions();
            newAction();
        }
    }
    
    0 讨论(0)
  • 2020-11-29 11:41

    One way is to take advantge of Aspect Oriented Programming (AOP). Have a look at PostSharp. Here is an example of using an exception attribute on a method so that if an exception happens, you can deal with it wihtout a try..catch block.

    EDIT:

    Ah yes, Dror's suggestion is also a good one. I've seen examples of that in the Enterprise Library. That would be better if you don't want to has a third party framework in your project (i.e. PostSharp).

    0 讨论(0)
提交回复
热议问题