How to filter exceptions with conditional breakpoints

This post originally appeared on Helper Code

 

With every new version the C# language has grown and improved.  C# 7 has brought some of my favorite features.

One of the new useful features added to C# is the ability to filter exceptions. Consider the following class:

 
public class MyClass 
{ 
	public void MyMethod(int count) 
	{ 
		// Logic here!
		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:

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 a 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 or 7 (yet?). For those cases I can use the magic of conditional breakpoints.

Using 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

Once you fix the bug you can delete the conditional breakpoint and carry on.

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.