How to ignore thrown exceptions

Yesterday I came across this question on StackOverflow:
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 code block, can't I simply "tag" it in such a way so as runtime knows which exceptions to neglect?
This question was first answered that ignoring exception automatically couldn’t and shouldn’t be done. Some of the answers stated that you should never even think about “automatically” catching exceptions because there is a reason they were thrown in the first place -  I don’t agree. There are instances when you want to silently ignore exception raised (log if necessary) them and continue executing your code (DTE I’m talking to you).
So if you have a valid reason for ignoring exceptions there are two ways to solve this problem one is using a n higher order function method and the other is PostSharp.

Solution #1 - Higher order function

“Higher order function” is a term related to functions that receive another function as an argument and/or return a function. By passing a function as argument you can add a simple try-catch block around it then execute it.
public void IgnoreExceptions(Action act)
{
    try
    {
        act.Invoke();
    }
    catch { }
}

And then the following line will ignore all exception thrown from Foo:

IgnoreExceptions(() => foo());

I prefer to pass the type of the exception just to make sure that I don’t accidently ignore the wrong exception type:

Solution #2 – Using PostSharp

I’ve written about PostSharp in the past it’s an AOP (Aspect Oriented Programming) framework for the .NET world. Using PostSharp you can create an attribute that would execute the decorated method using MethodInterceptionAspect:


public class IgnoreExpections : MethodInterceptionAspect
{
    public override void OnInvoke(MethodInterceptionArgs args)
    {
        try
        {
            args.Proceed();
        }
        catch { }
    }
}

Now all you need to do is to use that attribute on your method:

public class MyClass 
{
    [IgnoreExpections]
    public void MethodThatThrowsException()
    {
        throw new Exception();
    }
}

Of course you can pass specific exception types via the attribute’s constructor and from there the sky is the limit.

One final note

Just because you can doesn’t mean you should. So before you decorate all of your methods with IgnoreExceptions think if it’s a good idea – there is a place and time for anything – even ignoring exceptions.

Labels: , , ,