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

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

Related

VS 17 breaking on all exceptions

Visual Studio 2017 is (kind of suddenly) breaking on all exceptions. That means, if I deactivate them in the exceptions settings (pressing CTRL + ALT + E while debugging), the debugger still breaks on them. I don't know wether this is just a bug of VS I can't change and therefore have to live with, or wether there is a simple solution for it.
This is the exception settings window:
and this the exception VS breaks on:
By the way, I also tried that beautiful minus (nothing happens if I press it) or adding a impossible condition (VS still broke on the exception).
I also tested other exceptions (by simply throwing them), which I deactivated before, and they get thrown as well and I tested the same issue in other projects, where it appeared as well:
I actually even put the whole stuff into a try catch statement but VS still breaks:
InitializeComponent ();
try
{
var t = new Thread (() =>
{
while (!IsHandleCreated) {} //It breaks here (similiar to the screenshots)
while (true)
Invoke (new Action (() => Size = new Size ()));
});
while (true)
{
t.Start ();
Thread.Sleep (100);
t.Abort ();
}
}
catch (ThreadAbortException) { }
It doesn't appear in other IDEs (like Rider) on my PC and doesn't occurr on other PCs in VS. It didn't always occurr on my PC, it just started recently and only in debugging mode. And if I continue the execution (with F5) it just continues normally.
EDIT As I put the try catch inside the thread it behaved a little bit different (I'm sorry for putting pictures in here, but I think they're more expressive in that case):
Can anybody explain this behaviour?
EDIT It seems to be normal for ThreadAbortExceptions to break again at the end of a catch statement. However, VS still shouldn't break on this exception at all.
I was having a similar problem.
I fixed it by unchecking "Break when exceptions cross AppDomain or managed/native boundaries" in Tools > Options > Debugging > General
I fixed it by unchecking Enable Just My Code in Tools > Options > Debugging > General
I can't confirm whether this happens with other project types, but it happens to me consistently with (Visual Studio Tools for Python) VSTP.
Although it is less than satisfactory, it can at least silence the exceptions and allow you to continue working in peace until a better solution surfaces. In my case, it was nearly impossible to debug my code, since StopIteration breaks during every iteration.
Select Debug > Windows > Exception Settings or press Ctrl-Alt-E. Y
Right click anywhere on the Window and select Show Columns > Additional Actions. You will have an "Additional Actions" column appear if it doesn't already.
Right click on a specific exception you want to silence or click the top level checkbox to select an entire category of exceptions, i.e. Python Exceptions. Click Continue When Unhandled in User Code.
Repeat for each additional exception or category of exceptions.
I know it's a little late for this, but ThreadAbortException is different from all other exceptions, and requires some special handling, otherwise it is automatically re-thrown at the end of all catch blocks if you don't actually handle it the way it's supposed to be handled.

Visual Studio breaking when it should not be... Anyone know why?

A little background. I write many data conversion apps for various platforms, and am no novice to using breakpoints, exception handling etc.
I have a range of conversion type methods that will take an object input (usually used directly out of a sqldatareader) and convert it to a specific type output, with a default returned if unable to do a direct conversion. Here is an example:
public int? GetNullInt(object obj)
{
try
{
int blah = Convert.ToInt32(obj);
if (blah == 0)
return null;
else
return blah;
}
catch (Exception ex)
{
return null;
}
}
In this case I want to return null if the object is either not an int or is 0.
Now.. the problem is that even tho this code is wrapped in a try/catch, for some reason in this one single application (windows forms, C#, .NET 4.5.2), Visual Studio is breaking when the input string is not in an expected format. The break asks me if I want to break on this type of exception (check box unchecked), but no matter what settings I set, it keeps breaking, even though I am catching the exception (can set a breakpoint in the catch and "continue" to it, so I know the try/catch is functioning). I have "Reset to default" the exception settings in VS, still no joy.
Now I know I can change this method slightly to use int.TryParse (and I am going to do that now), but that does not solve the underlying problem of why VS is breaking in the first place, since this was NOT an unhandled exception.
Any ideas?
(here is a screenshot of the break)
Photo of the break happening at runtime
In visual studio you have new window called Exception settings.
This window appears after pressing Ctrl + Alt + E.
In this window you can set the Exception handling.
You code is working fine in my Visual Studio Desktop For Express 2015.
You just need to uncheck all the things in this window.
Please refer an Image.
You can refer below post, this is exactly same which you want.
Visual Studio 2015 break on unhandled exceptions not working
From the look of your screenshot you do not have "Just My Code" enabled in the debugger settings
If that setting is not enabled you can't use the "Only catch unhandled exceptions" feature of visual studio.

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

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.

How to NOT breaking on an exception?

I've got something like this:
try
{
instance.SometimesThrowAnUnavoidableException(); // Visual Studio pauses the execution here due to the CustomException and I want to prevent that.
}
catch (CustomException exc)
{
// Handle an exception and go on.
}
anotherObject.AlsoThrowsCustomException(); // Here I want VS to catch the CustomException.
In another part of code I have multiple occurencies of situations where CustomException is thrown. I would like to force the Visual Studio to stop breaking on instance.SometimesThrowAnUnavoidableException() line cause it obscures the view of other places where I'm interested in breaking on CustomException.
I tried DebuggerNonUserCode but it is for a different purpose.
How to disable Visual Studio from catching particular exception only in a certain method?
You can use custom code to do this in two steps.
Disable automatic breaking on the CustomException exception.
Add a handler for the AppDomain.FirstChanceException event to your application. In the handler, if the actual exception is a CustomException, check the call stack to see if you actually want to break.
Use the Debugger.Break(); to cause Visual Studio to stop.
Here is some example code:
private void ListenForEvents()
{
AppDomain.CurrentDomain.FirstChanceException += HandleFirstChanceException;
}
private void HandleFirstChanceException(object sender, FirstChanceExceptionEventArgs e)
{
Exception ex = e.Exception as CustomException;
if (ex == null)
return;
// option 1
if (ex.TargetSite.Name == "SometimesThrowAnUnavoidableException")
return;
// option 2
if (ex.StackTrace.Contains("SometimesThrowAnUnavoidableException"))
return;
// examine ex if you hit this line
Debugger.Break();
}
In Visual Studio, go to debug->exceptions and turn off breaking for your CustomException by unchecking the appropriate checkbox, then set a breakpoint in the code (probably on the catch statement) on the places you actually want to break on.
If you want Visual Studio to stop breaking on all exceptions of a type, you have to configure the behavior from the Exceptions window.
Full instructions are here, but the gist is to go to the Debug menu and choose exceptions, then uncheck the items you dont want the debugger to break on.
I don't think there is a way to avoid a specific method using this technique, but maybe the better question is "why is this throwing an exception?"
You could add a set of #IF DEBUG pre-processor instructions to avoid running the problematic sections of code.
You can disable stepping altogether by placing the DebuggerStepThrough Attribute before the method.
As this disables stepping in the whole method, you may isolate the try-catch into a seperate one for debugging purposes.
I did not test, but it should not even break in that method when en exception is thrown. Give it try ;-)
See also this SO thread
You can't simply disable Visual Studio from stoping in a particular place of code. You can only prevent it to stop when particular type of exception is thrown but that will affect all places where such exception occurs.
Actually you can implement custom solution as suggested by 280Z28.

Categories