Search code examples
.netexceptionlambdatry-catchconditional-compilation

Conditional compilation for try catch


I have been using conditional compilation as a way to allow me to debug easily (by removing the try catch block) with production code. The reason I do this is because visual studio will (obviously) show the location of the exception thrown as being the catch block of the topmost handler. This unfortunately prevents debugging or at least locating the exact location of the error until you remove the handler.

Here is an example of my current approach

    private void btnConnect_Click(object sender, EventArgs e)
    {
#if DEBUG
        DoSomething();
#else
        try 
        {
            DoSomething();
        } 
        catch (Exception ex) 
        {
            Logger.Log(ex);
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally 
        {
            CleanUp();
        }
#endif
    }

This approach causes significant duplication of code and I am hoping to find an alternative.

I have considered an approach where I would use lambdas to create a custom try catch block handler that internally uses conditional compilation to either handle or rethrow the exception like this.

    void TryCatchFinally(Action tryBlock, Action<Exception> catchBlock, Action finallyBlock)
    {
#if DEBUG
        tryBlock.Invoke();
        finallyBlock.Invoke();
#else 
        try
        {
            tryBlock.Invoke();
        }
        catch (Exception ex)
        {
            catchBlock.Invoke(ex);
        }
        finally
        {
            finallyBlock.Invoke();
        }
#endif
    }

But I would prefer to keep the standard try catch syntax (Plus this approach would mean that I couldn't apply it to existing code without major changes)

Has anyone found a good approach to this issue or can anyone think of an improvement on my version?


Solution

  • I'm not sure why you need to do this - I've never seen someone approach debugging exceptions like this.

    Are you aware you can configure Visual Studio to break when the exception is thrown without needing different code paths?

    Debug->Exceptions->Check "Thrown"

    If I've understood the question correctly - then this solves your problem for debugging in VS.