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

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.

Related

Code throws NullReferenceException, but catch block not able to catch the exception

The code is intentionally written to throw a NullReferenceException, where the main list is initialised but the sub-lists inside the main list are not initialised.
Code is as follows:
List<List<string>> myList01 = new List<List<string>>(new List<string>[3]);
string[] myFruits = new string[3] { "apple", "banana", "citron" };
try
{ myList01[0].Add(myFruits[0]); }
catch (NullReferenceException e)
{ Console.WriteLine(e.Message); }
NullReferenceException was thrown, but not caught by the catch block, as shown below
Why is this happening? How to let the catch block catch this exception?
No, the exception is not caught in this case
Well, it would be caught if the code had progressed as far as handling the throw, but it hasn't yet. It will if you press F10 etc
It's breaking as soon as the exception is thrown because you've told VS to break when it's thrown:
Nominating an exception for "Break When Thrown" means as soon as it happens, VS stops what it's doing and opens the exception helper. It doesn't run any catch handler or anything. It literally stops immediately to tell you. If you then step/run the code you'll see control jump to the catch..
#Chandana System.NullReferenceException is ticked in the Exception Settings.
It needs to be unticked - these are the settings for "Break When Thrown" which is different to "Break When Unhandled" (i.e. an exception occurs and there is nowhere a catch that will deal with it)
When you're running with it ticked you'll see:
If you press F10, VS jumps to the handler and the wording changes:

C# crashes despite try/catch block [duplicate]

I would like Visual Studio to break when a handled exception happens (i.e. I don't just want to see a "First chance" message, I want to debug the actual exception).
e.g. I want the debugger to break at the exception:
try
{
System.IO.File.Delete(someFilename);
}
catch (Exception)
{
//we really don't care at runtime if the file couldn't be deleted
}
I came across these notes for Visual Studio.NET:
1) In VS.NET go to the Debug Menu >>
"Exceptions..." >> "Common Language
Runtime Exceptions" >> "System" and
select "System.NullReferenceException"
2) In the bottom of that dialog there
is a "When the exception is thrown:"
group box, select "Break into the
debugger"
3) Run your scenario. When the
exception is thrown, the debugger will
stop and notify you with a dialog that
says something like:
"An exception of type "System.NullReferenceException" has
been thrown.
[Break] [Continue]"
Hit [Break]. This will put you on the
line of code that's causing the
problem.
But they do not apply to Visual Studio 2005 (there is no Exceptions option on the Debug menu).
Does anyone know where the find this options dialog in Visual Studio that the "When the exception is thrown" group box, with the option to "Break into the debugger"?
Update: The problem was that my Debug menu didn't have an Exceptions item. I customized the menu to manually add it.
With a solution open, go to the Debug - Windows - Exception Settings (Ctrl+Alt+E) menu option. From there you can choose to break on Thrown or User-unhandled exceptions.
EDIT: My instance is set up with the C# "profile" perhaps it isn't there for other profiles?
There is an 'exceptions' window in VS2005 ... try Ctrl+Alt+E when debugging and click on the 'Thrown' checkbox for the exception you want to stop on.
Took me a while to find the new place for expection settings, therefore a new answer.
Since Visual Studio 2015 you control which Exceptions to stop on in the Exception Settings Window (Debug->Windows->Exception Settings). The shortcut is still Ctrl-Alt-E.
The simplest way to handle custom exceptions is selecting "all exceptions not in this list".
Here is a screenshot from the english version:
Here is a screenshot from the german version:
From Visual Studio 2015 and onward, you need to go to the "Exception Settings" dialog (Ctrl+Alt+E) and check off the "Common Language Runtime Exceptions" (or a specific one you want i.e. ArgumentNullException) to make it break on handled exceptions.
Step 1
Step 2
Check Managing Exceptions with the Debugger page, it explains how to set this up.
Essentially, here are the steps (during debugging):
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.
A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:
if(!GlobalTestingBool)
{
try
{
SomeErrorProneMethod();
}
catch (...)
{
// ... Error handling ...
}
}
else
{
SomeErrorProneMethod();
}
I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.
The online documentation seems a little unclear, so I just performed a little test. Choosing to break on Thrown from the Exceptions dialog box causes the program execution to break on any exception, handled or unhandled. If you want to break on handled exceptions only, it seems your only recourse is to go through your code and put breakpoints on all your handled exceptions. This seems a little excessive, so it might be better to add a debug statement whenever you handle an exception. Then when you see that output, you can set a breakpoint at that line in the code.
There are some other aspects to this that need to be unpacked. Generally, an app should not throw exceptions unless something exceptional happens.
Microsoft's documentation says:
For conditions that are likely to occur but might trigger an exception, consider handling them in a way that will avoid the exception.
and
A class can provide methods or properties that enable you to avoid making a call that would trigger an exception.
Exceptions degrade performance and disrupt the debugging experience because you should be able to break on all exceptions in any running code.
If you find that your debugging experience is poor because the debugger constantly breaks on pointless exceptions, you may need to detect handled exceptions in your tests. This technique allows you to fail tests when code throws unexpected exceptions.
Here are some helper functions for doing that
public class HandledExceptionGuard
{
public static void DoesntThrowException(Action test,
Func<object?, Exception, bool>? ignoreException = null)
{
var errors = new List<ExceptionInformation>();
EventHandler<FirstChanceExceptionEventArgs> handler = (s, e) =>
{
if (e.Exception is AssertFailedException) return;
if (ignoreException?.Invoke(s, e.Exception) ?? false) return;
errors.Add(new ExceptionInformation(s, e.Exception, AppDomain.CurrentDomain.FriendlyName));
};
AppDomain.CurrentDomain.FirstChanceException += handler;
test();
AppDomain.CurrentDomain.FirstChanceException -= handler;
if (errors.Count > 0)
{
throw new ExceptionAssertionException(errors);
}
}
public async static Task DoesntThrowExceptionAsync(Func<Task> test,
Func<object?, Exception, bool>? ignoreException = null)
{
var errors = new List<ExceptionInformation>();
EventHandler<FirstChanceExceptionEventArgs> handler = (s, e) =>
{
if (e.Exception is AssertFailedException) return;
if (ignoreException?.Invoke(s, e.Exception) ?? false) return;
errors.Add(new ExceptionInformation(s, e.Exception, AppDomain.CurrentDomain.FriendlyName));
};
AppDomain.CurrentDomain.FirstChanceException += handler;
await test();
AppDomain.CurrentDomain.FirstChanceException -= handler;
if (errors.Count > 0)
{
throw new ExceptionAssertionException(errors);
}
}
}
If you wrap any code in these methods as below, the test will fail when a handled exception occurs. You can ignore exceptions with the callback. This validates your code against unwanted handled exceptions.
[TestClass]
public class HandledExceptionTests
{
private static void SyncMethod()
{
try
{
throw new Exception();
}
catch (Exception)
{
}
}
private static async Task AsyncMethod()
{
try
{
await Task.Run(() => throw new Exception());
}
catch (Exception)
{
}
}
[TestMethod]
public void SynchronousTest()
{
HandledExceptionGuard.DoesntThrowException(() => SyncMethod());
}
[TestMethod]
public async Task AsyncTest()
{
await HandledExceptionGuard.DoesntThrowExceptionAsync(() => AsyncMethod());
}
}

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.

Debugger does not break the code when exceptions are thrown

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

C# - Application terminates unexpectedly without leaving traces

I have a simple C# application/game using SFML.Net that currently stops running / terminates within 1 or 2 seconds after being executed without any warning, exception, etc. whatsoever. Consider the following code:
public static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
--> The following two lines are run
Console.WriteLine("Hello");
Console.WriteLine("Please don't go...");
// Run the game
try
{
--> This line is reached
Game.Run();
}
catch (Exception e)
{
--> This line is never reached
Console.WriteLine(e.Message.ToString());
}
--> These lines are never reached
Console.WriteLine("Noone ever comes here, I feel so lonely... :(");
Console.ReadKey();
}
}
At this point you probably expect that something is wrong with the Game.Run() method. The odd thing is that the first line of the method is never reached according to the VS Debugger.
public static void Run()
{
try
{
--> Never reached
LoadContent();
// Do stuff here
while (window.IsOpen())
{
// The classic game loop
}
}
catch (Exception e)
{
--> Never reached
Console.WriteLine(e.Message.ToString());
Console.ReadKey();
}
}
My guess is that either:
You are getting an Access Violation Exception which cannot be caught.
OR
There is some other exception before you go into the Run method that is not handled. In order to verify that, make sure your debugger stops on first chance exceptions.
It would also be helpful if you specify:
How do you know that the first line is never reached? breakpoint? output?
What happens when you expect this function to be entered? does your application exist?
Are you debugging step by step?
My Guess is that the exception is being thrown by another thread. You cannot catch an exception thrown from another thread in the main thread. So your breakpoint in catch will never be hit. Btw did you try having a breakpoint in your UnhandledExceptionEventHandler method OnUnhandledException? That is where all unhandled exceptions go! Hope this helps.
You can get all called functions stack in your application until the termination point with the Runtime Flow tool (30 day trial, developed by me) and find what actually happens.
I came back to this after a couple of months and realized how silly my mistake was. Apparently unmanaged code debugging wasn't enabled by default (this was my first time using VS2012), and this exception was being thrown from the base C++ libs of SFML.
For those who don't know, to enable unmanaged debugging:
Project > Properties > Debug > Select "Enable unmanaged code debugging"

Categories