Debugger does not break the code when exceptions are thrown - c#

When debugging my Winform program, I recently found that instead of breaking in the source code lines that do bad, the program will pop up a dialog showing error message, something like below:
This is not good for me as I didn't know where in the code that caused this failure, do you know why my Visual Studio debugger behaves like this and how can I alter this?

if you are running your application in Non-Debug mode it will not break your code ,it just displays the error message in MessageBox
if you want to throw exception and point to your code exactly where exception raised you need to Run you program in Debug mode.
EDIT: if you are already in Debug mode try this:
Step 1: Goto Debug menu in VS IDE
Step 2: Select Exceptions
Step 3: now You need to check the Common Language Runtime Exceptions option in Exceptions dialog.

I guess you catch exceptions in your program and show a message box in that case. Probably with a blanket catch (Exception e). You can make the debugger to break into any exception thrown, even if caught under Debug > Exceptions.

You could show the StackTrace instead of the Message, which contains a drill down to the call that caused the exception.
You could show your message like this:
try
{
// some code that throws an exception
}
catch()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Message: {0}", e.Message);
sb.AppendLine();
sb.AppendLine();
sb.AppendFormat("StackTrace: {0}", e.StackTrace);
MessageBox.Show(sb.ToString(), "Error");
}

Related

Visual Studio - suppress certain "Exception thrown" messages

Can you hide "Exception thrown" messages in output for certain methods (certain code areas)?
I use HttpWebRequest for server communication. I periodically check if the server is available (a few times every second). When a server is not reachable HttpWebRequest throws an exception. I catch it and set GUI elements enabled to false. The problem is when the server is unreachable, output window gets cluttered up with "Exception thrown" messages.
I know you can right-click output window and uncheck "Exception Messages". But I am not only one working on the project and there might be someone who wants to see some other exception messages (in their part of the project).
Example of what I need:
// Keep showing "Exception thrown" message in this method.
static void Foo()
{
try
{
throw new NotImplementedException();
}
catch (NotImplementedException ex)
{
// Process exception
}
}
// Suppress "Exception thrown" message when it is thown in this method.
static void FooSuppress()
{
try
{
throw new ArgumentException();
}
catch (ArgumentException ex)
{
// Process exception
}
}
static void Main(string[] args)
{
Foo();
FooSuppress();
}
Current output:
Exception thrown: 'System.NotImplementedException' in ExceptionTest.dll
Exception thrown: 'System.ArgumentException' in ExceptionTest.dll
Desired output:
Exception thrown: 'System.NotImplementedException' in ExceptionTest.dll
Edit:
Enabling Just my code in Tools/Options/Debugging might help.
We used Npgsql to access PostgreSQL database and some calls had timeout. Everytime call timeouted "Exception thrown" was written to output window (and there were a lot). Just my code prevents that.
To disable the Exception messages:
(1)Like your previous reply, you could disable it in the Output windows.
(2)You could also disable it under TOOLS->Options->Debugging->Output Window.
(3)Or you could just throw the Exception using the Exception Settings under Debug menu->Windows->Exception Settings.
I don't find other workaround to disable it unless you really resolve/handle the Exceptions in your code. I test it using the VS2015 version.
No other good suggestion, but I help you submit a feature here: https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/16752127-visual-studio-suppress-certain-exception-thrown-me
You could vote it.
If you are willing to wait a little bit or use a pre-release version, the next version of Visual Studio (VS 15) will have a feature "Add Conditions to Exception Settings"
Add Conditions to Exception Settings When you configure the
debugger to break on thrown exceptions, you can add conditions so that
the debugger will only break when exceptions are thrown in specified
modules.
This will allow you to set filters on when exceptions should break.

C# stop on error line within try catch [duplicate]

This question already has answers here:
Visual Studio: How to break on handled exceptions?
(8 answers)
Closed 8 years ago.
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);
}
}
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.
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.
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.
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.

Application does not exit after Exception is thrown

I have unusual (for me) problem with thrown exception. After exception is thrown application loops on it and doesn't exit.
if(!foundRemoteID)
{
throw new ArgumentOutOfRangeException(
"value",
"Remote ID was not found."
);
}
I have inserted brakepoint on "if(!foundRemoteID)" line but the program doesn't hit it at all after firs thrown exception. It just loops over and over on "throw new (..).
-I do not have try{} catch{} blocks at all at any level.
-There is no loop that contains this code
I have even tried putting it into:
try
{
(..)
}
finally
{
Enviroment.Exit(1);
}
but finally{} block is never hit.
Other throw new (..) in this class is acting same way.
Am I missing something trivial?
UPDATE:
Problem is not related to my project. I have just created a simple console application that has only
throw new FileNotFoundException();
In Main() method and problem persists.
I have already tried resetting VS2010 settings to default and it didn't help.
Most likely this is not the actual behavior of your application - rather, Visual Studio is set to always break when there is an unhandled ArgumentOutOfRangeException.
You can verify this by pressing "Start without debugging".
If you want to change the settings, browse to the menu to Debug -> Exceptions and you should see the following. Then uncheck "User-unhandled."
Personally, I recommend leaving the setting the way it is in most cases. It really helps when hunting down unhandled exceptions.

Exception handling c# doesn't behave as I expect -- why?

I have the following C# code:
try
{
response = this.writeDataToChannel(writeRequest);
if (response.Failures != null)
{
Console.WriteLine(response.Failures.First().cause);
}
}
catch (TimeoutException te)
{
Console.Error.WriteLine(te.Message);
}
When I run this code in release and push a lot of data to the service, VS2010 stops on the "writeDataToChannel" line with a TimeoutException. Shouldn't my catch block catch the exception and just print it when the timeout happens?
The "writeDataToChannel" code was generated from a WSDL, the writes always work until I push tons of data to the webservice, so I don't think there is a problem with my request.
It is not a namespace issue, in both cases it is a System.TimeoutException.
It sounds to me like you have Visual Studio set to stop on a thrown exception. Go to the menu item Debug->Exceptions and see what your CLR Exceptions settings are. To get the behavior that you're describing, you don't want to stop on caught or uncaught exceptions.
Alternatively, don't run it under the debugger.
You probably need to tell VS to not break on each thrown exception in the exceptions dialog (ctrl + alt + e and uncheck CLR exceptions)
As others have mentioned, this happens when you are debugging the project (by hitting F5, or clicking the green triangle button ">").
To run without debugging, type CTRL + F5, or click the "Start without debugging" menu choice or button.
You don't necessarily need to remove the option to stop on exceptions like others have mentioned, but go ahead and do so if it becomes annoying.
You will need to throw in order to catch something in your try/catch
throw

Make Visual Studio ignore exceptions?

I'm using exceptions to validate a control's input in Silverlight 4. When I throw an invalid input exception, VS 2010 displays the popup and stops the program. I ignore this and resume the program, and everything continues fine (since the exception is used to signal a validation error.) Is there a way to mark that one exception as ignored?
I'm following this tutorial.
Debug -> Exceptions -> Uncheck
Menu, Debugger, Exceptions...
In that dialog, you can remove the checkmark in the 'thrown' column for one exception, of for a whole namespace. You can add your own. etc.etc.
I got [System.Diagnostics.DebuggerHidden()] to work if I also selected
Debug > Options > Debugging > General > Enable Just My Code (Managed only).
I access the Excel object model a lot, and I really like to be able to run the debugger and catching all exceptions, since my code normally is exception less. However, the Excel API throws a lot of exceptions.
// [System.Diagnostics.DebuggerNonUserCode()] works too
[System.Diagnostics.DebuggerHidden()]
private static Excel.Range TrySpecialCells(Excel.Worksheet sheet, Excel.XlCellType cellType)
{
try
{
return sheet.Cells.SpecialCells(cellType);
}
catch (TargetInvocationException)
{
return null;
}
catch (COMException)
{
return null;
}
}
When you run Visual Studio in debug mode, there are Exception Setting on the bottom tool bar. Once you click it, there are all type exceptions. Uncheck exceptions that you want. For the Custom exception you made for this project, they are located in Common Language Runtime Exceptions, at very bottom. Hope this helpful.
You can disable some throw block by surrounding in the block
#if !DEBUG
throw new Exception();
/// this code will be excepted in the debug mode but will be run in the release
#endif
Putting this above the property that throws the exception seems like it should work but apparently doesn't:
[System.Diagnostics.DebuggerHidden()]:
private String name;
[System.Diagnostics.DebuggerHidden()]
public String Name
{
get
{
return name;
}
set
{
if (String.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("Please enter a name.");
}
}
}
From Visual Studio 2015 onward there is an Exception Settings window for this.
Debug > Windows > Exception Settings

Categories