views:

177

answers:

4

If I have a nested loop scenario and I am stepping into it in debug mode. Ex:

for (int i = 0; i < listTest.Count; i++)
{
   for (int j = 0; j < anotherList.Count; j++)
   {
      //Some logic that throws an exception
   }
}

Is there a way for me to know the values of i, j, listTest[i] and anotherLIst[j] just before the exception occurred? If the count values are high, it's impractical to loop through the loops and watch these values before the exception occurs

+1  A: 

Surround all the code inside the second loop with a try/catch block. Catch the exception and rethrow it. Place your breakpoint on the line within the catch. When the exception occurs, i and j should be the value at the time of the exception.

JasCav
+2  A: 

First, you could change the settings in VS2008 to break on exception when thrown:

Debug >> Exception >> Common Language Runtime Exceptions Dialog

This will cause the debugger to stop on the line of code that generates the offending exception, and i and j should be in scope at that point.

You could also promote the loop variables i and j outside of the loops; like so:

int i, j;
for (i = 0; i < listTest.Count; i++)
{
   for (j = 0; j < anotherList.Count; j++)
   {
      //Some logic that throws an exception
   }
}
LBushkin
One of the hidden gems of VS.
Adrian Godong
You Beat me to it
Justin
+1  A: 

You can setup Visual Studio to break for all exceptions. In Visual Studio goto Debug->Exceptions in the menu. The check to break when an exception is thrown for Common Language Runtime Exceptions. This will cause it to break here without a catch.

Note: You probably don't want this on all the time, and if you are using logic that could possible throw an exception you should be using a try/catch.

Justin
A: 

Need Help:

I'm trying to create a 3x3 checkers board or a chess board.

this is my code for printing a 3 blocks horizontally.

> Graphics^ block;

int i; for(i=0;i<=2;i++) { block->DrawRectangle(Pens::Black, 0 , 0+i*50 , 50 , 50) } << I tried using a for loop and was able to display 5 blocks horizontally. The question is how do i print these 3 blocks vertically? Making it 3x3 block