0

If I run the code below that calls Test1(), VS2012 will break nicely at that line and show me exactly what's going on. If I comment out Test1 and put in Test2, then the try catch does not stop on the line, it just logs it out to the console.

How can I get VS2012 to stop on the error line, even when it is surrounded by a try catch statement?

private void Button_Click(object sender, RoutedEventArgs e)
{
  //Test1(); // No try catch - stops on error line dividing by zero.
  Test2(); // Try catch - Just writes out to console.
}

private void MakeError()
{
  int i = -1;
  i += 1;
  int j = 1 / i;
  Console.WriteLine(j.ToString());
}

void Test1()
{
  Console.WriteLine("MakeError in Test1");

  MakeError();
}

void Test2()
{
  Console.WriteLine("MakeError in Test2");
  try
  {
    MakeError();
  }
  catch (Exception ex)
  {
    Console.WriteLine(ex.Message);
  }
}
Dean
  • 731
  • 8
  • 21
  • The confusion for me was that the list of units (for example System, System.ComponentModel, etc) did not look like it had an entry for my own code - meaning code that I write myself. But now I see that the exception for Divide By Zero is actually defined in the System unit, so checking the Thrown check box in that one place is enough to make it break on the sample error posted here. None of this was obvious to me even after searching for a while, so I will leave the topic here and hope that some others can find it useful. – Dean May 30 '14 at 03:01

4 Answers4

5

While the other answers are correct, this is the intentional behavior by default, you can tell Visual Studio to alert you to those exceptions if you wish.

How to: Break When an Exception is Thrown:

On the Debug menu, click Exceptions.

In the Exceptions dialog box, select Thrown for an entire category of exceptions, for example, Common Language Runtime Exceptions.

-or-

Expand the node for a category of exceptions, for example, Common Language Runtime Exceptions, and select Thrown for a specific exception within that category.

Justin Helgerson
  • 24,900
  • 17
  • 97
  • 124
1

What you want is Visual Studio break execution when an exception is thrown:

On the Debug menu, click Exceptions.

In the Exceptions dialog box, select Thrown for an entire category of exceptions, for example (your case), Common Language Runtime Exceptions.

MSDN Reference.

quantdev
  • 23,517
  • 5
  • 55
  • 88
0

Visual Studio will only intervene when there is an unhandled exception , in this case a division by 0. The try...catch handled the exception. Since there is no exception left unhandled, Visual Studio will not jump out.

Xiaoy312
  • 14,292
  • 1
  • 32
  • 44
0

try and catch statements are intended so that the flow of execution can still happen, even when an exception occurs. The debugger only stops when the exception is unhandled, which the try catch does.

This is intentional.

Justine Krejcha
  • 1,235
  • 17
  • 27