Make Visual Studio ignore exceptions? - c#

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

Related

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 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.

How to make [DebuggerNonUserCode] hide an exception from the debugger in simple test case?

Setup:
1) MSVS 2015, Option -> Debugger -> "Just My Code" is checked.
2) This sample code placed within some class and called during startup:
static bool TestIgnoreException()
{
Exception ex;
return TrySomething(out ex);
}
[DebuggerNonUserCode] // Prevent exceptions from stopping the debugger within this method.
static bool TrySomething(out Exception exOut)
{
try
{
if (Environment. MachineName.Length != -1)
throw new Exception("ThrewIt.");
exOut = null;
return true;
}
catch (Exception ex)
{
exOut = ex;
return false;
}
}
3) Launch Debugger
Expected result is that TestIgnoreException() runs silently and returns false.
Actual result is the debugger stops in TestIgnoreException() even though there should be no exception being processed at that scope.
4) Also re-tried using [DebuggerHidden] instead, same results.
Motivation:
The motivation is for cases where some API that is out of your control does not provide a "Try" method and instead only indicates failure by using exceptions.
One of numerous such examples is .NET TcpClient.Connect(host, port). Say a program always tests some connections during startup, the debugger should not stop on this particular section of code each time.
Using the standard "break when thrown" exceptions checkboxes is is not good because it works globally by type. It cannot be configured to work locally. Also other developers who check out the code should automatically skip the exception as well.
Mystery solved. It is indeed a known issue that is new to MSVS 2015 because of added exception handling optimizations.
https://blogs.msdn.microsoft.com/visualstudioalm/2016/02/12/using-the-debuggernonusercode-attribute-in-visual-studio-2015/#
There is a workaround posted on that link to disable the optimizations and enable the old behavior. Hopefully they will eventually be able to revive the support for this including the optimizations.
reg add HKCU\Software\Microsoft\VisualStudio\14.0_Config\Debugger\Engine /v AlwaysEnableExceptionCallbacksOutsideMyCode /t REG_DWORD /d 1
Related question:
Don't stop debugger at THAT exception when it's thrown and caught

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