Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force an exception while debugging in Visual Studio?

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.

like image 769
Ryan Kohn Avatar asked Dec 13 '12 16:12

Ryan Kohn


People also ask

How do I skip the code while debugging in Visual Studio?

You can also click on the line you want to skip to and hit Ctrl+F10 (Run to Cursor). It will jump directly to that line.

How do I force stop debugging in Visual Studio?

To end a debugging session in Microsoft Visual Studio, from the Debug menu, choose Stop Debugging.


2 Answers

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.

like image 189
Ryan Kohn Avatar answered Sep 18 '22 12:09

Ryan Kohn


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")

like image 25
Belogix Avatar answered Sep 19 '22 12:09

Belogix