views:

52

answers:

3

I have two FOR loops that the outer will repeat 64 times some where I know there is a index out of bound error How can I set a good break point or try/catch block,etc that exactly shows me the index and line of code that is causing the problem. ( C# WinApp)

Thanks all.

+2  A: 

If you're using Visual Studio the simplest way is to just hit F5. The debugger will automatically break on exceptions thrown by your code which is not being caught.

This won't necessarily work if the exception is being caught elsewhere in your code. If that is the case you can enable break on exceptions by going to

  • Debug -> Exceptions
  • Check "User Thrown" for CLR exceptions
  • Hit F5
JaredPar
+6  A: 

In the VS debugger, you can just enable "Break On Thrown Exception" in the Exceptions dialog. Then you don't need to set a breakpoint, the debugger will automatically stop when the exception is raised.

You make this change in: Debug >> Exceptions >> Common Language Runtime Exceptions

Just check the appropriate exception in the "Thrown" column in the dialog:

alt text

If you need to break before the exception is raised (let's say to inspect some volatile data), it's possible to set conditional breakpoints on a particular line that only breaks when some condition in your code is true. To do this, you can set a regular breakpoint and then right click on the red circle icon in the margin and select: [Condition...].

This brings up the conditional breakpoint dialog where you can write an expression that will cause the debugger to break when evaluated to true (or when some value changes). Breakpoint conditions can be a bit finicky, but if you stick to simple variables in your code it works well.

alt text

LBushkin
Thanks Sir, I will try this now, looks like it does what I need. I am also copy-pasting the code in the comments of previous replies to this question.
BDotA
That was awesome :) and I could look at CallStack to see what line caused it.
BDotA
Didnt know this, you seem to be an expert in Visual Studio, thanks...
Akash Kava
+2  A: 

[ I think the other answers are better for this particular problem, but I'm leaving this because of the scoping considerations. ]

For quick debugging, go inside the loop so your loop variable will still be in scope and populated.

int[] array = new int[10];

for (int i = 0; i < 20; i++)
{
    try
    {
        int temp = array[i];
    }
    catch (IndexOutOfRangeException ex)
    {
        // i is still in scope
    }
}
Anthony Pegram