Using conditional breakpoints to filter exceptions during debugging

Wednesday, November 09, 2016

With every new version the C# language has grown and improved. The last version so a.k.a C# 6 has brought some of my favorite features. And with C# 7 just around the corner I know there's more to come.

One of the new useful features added to C# is the ability to filter exceptions. Consider the following - completely (and poorly) invented class:

public class MyClass 
public class MyClass
{
    public void MyMethod(int count)
    {
        throw new MyException(1000 + count);
    }
}

If I need to exit only when an exception with a specific error code is thrown I can write the following code:

class Program
{
    static void Main(string[] args)
    {
        var myClass = new MyClass();

        for (int i = 0; i < 10; i++)
        {

            try
            {
                myClass.MyMethod(i);
            }
            catch (MyException ex) when (ex.ErrorCode == 1003)
            {
                Console.WriteLine($"Got the right exception in iteration: {i}");
                break;
            }
            catch (MyException ex)
            {
                Console.WriteLine($"Other exception: {ex.ErrorCode}");
            }
        }
    }
}

And each exception with value which is not 1003 will be swallowed. There are limitless scenarios in which this feature can be useful - for example have a look at Jimmy Bogard's post on how to avoid exceptions on the weekends.

But what happens when I need the same functionality but just for a specific debug session or if I'm working on a project which does not use C# 6 (yet?). For those cases I can use the magic of conditional breakpoints.

Filtering with conditional breakpoints

There are two ways to set a conditional breakpoint - the old way and the OzCode way.

If you never used them - you should; it's a time saving tool which will save you valuable debug time.

In order to use Conditional breakpoints just create a regular breakpoint at the exception's constructor and then add condition to that breakpoint - simple as that. With OzCode it's even easier:

  1. Create a "regular" breakpoint at the exception's constructor
  2. Run until breakpoint
  3. Open the quick watch window
  4. Choose the property you care about
  5. Update the condition
  6. Press "ok" and run

 

Conditional_breakpoints

Once you fix the bug you can delete the conditional breakpoint and continue working – or find and fix another bug.

Conclusion

Conditional breakpoints have been part of your favorite IDE of choice for ever and yet not all developers use them as often as they should. Catching just the right exception is one scenario where they help find and fix bugs and save us time in which we can develop new features for our customers or just grab another cup of coffee.

No comments

Post a Comment

Newer Older
Related Posts Plugin for WordPress, Blogger...