Using Conditional Breakpoints to Filter Exceptions During Debugging
Did you know that with C# 6 you can now filter exceptions? Well, you can! Read on to find out how to make use of this handy new feature.
Join the DZone community and get the full member experience.
Join For FreeWith 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:
- Create a "regular" breakpoint at the exception's constructor
- Run until breakpoint
- Open the quick watch window
- Choose the property you care about
- Update the condition
- Press "ok" and run
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 forever 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.
Published at DZone with permission of Dror Helper, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments