How to force an exception while debugging in Visual Studio?

C#.NetVisual Studio

C# Problem Overview


I am running my application in debug mode, and I would like to manually throw an exception (i.e. not from within the code). Is there any way to do this?

Of course, running throw new Exception("My forced exception"); in the Command or Immediate window doesn't work.

EDIT: I want the exception to be caught by the try-catch statement that surrounds the code I'm debugging.

C# Solutions


Solution 1 - C#

One possible way is to break on a line and manually change a nullable variable in the code path to null just before an operation on it occurs. This will cause a NullReferenceException to be thrown.

Solution 2 - C#

You could add a method similar to:

public static void ThrowAnException(string message)
{
    throw new ApplicationException(message);
}

Then, using the Immediate window, you could call ThrowAnException("Whoops")

Solution 3 - C#

If you're running within the context of a unit test, and the point where you want the exception to originate is behind an injected interface or class, you can create a mock object that throws the exception.

The advantage of this is, once you're happy that you've replicated the error, you can construct a new unit test for your regression suite.

Solution 4 - C#

Try to use the immediate window while you are on a break point.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyan KohnView Question on Stackoverflow
Solution 1 - C#Ryan KohnView Answer on Stackoverflow
Solution 2 - C#BelogixView Answer on Stackoverflow
Solution 3 - C#Giles RobertsView Answer on Stackoverflow
Solution 4 - C#LocalghostView Answer on Stackoverflow