Freigeben über


Silencing Exceptions in a Little Better Way

Some of the most disastrous code usually takes the following form

 try
{
    //some code
}
catch
{ }

Silencing exceptions is almost never good but sometime the problem is minor and you don’t want want to blow up and call for an exit. However wouldn’t it be better if exceptions don’t remain silent and scream for your attention when you are debugging and behave less aggressively otherwise?

How about if we can replace above code with following:

 IgnoreExceptionButNotIfDebugging(() =>
{
    //some code
});

Better.

The mysterious IgnoreExceptionButNotIfDebugging is a simple method that takes lambda and it would look like below:

 

 public static void IgnoreExceptionButNotIfDebugging(Action codeBlockToExecute)
{
    try
    {
        codeBlockToExecute();
    }
    catch (Exception ex)
    {
        if (Debugger.IsAttached)
            Debugger.Break();

        Trace.Write("Exception occured: " + ex.Message);

        EventLog.WriteEntry("MyApp", ex.Message, EventLogEntryType.Warning);

#if DEBUG
            throw;
#endif
    }
}

Now you can surround any of your code by IgnoreExceptionButNotIfDebugging and make sure things don’t remain silent when you are debugging!