I set my Visual Studio Exception Settings to Break When 'Common Language Runtime Exceptions' are thrown.
I have numerous routines where I catch exceptions, handle them and continue. When I'm debugging my program, I trust that these exceptions have been correctly handled and do not want the debugger to stop on them.
How can I prevent the debugger from stopping on handled exceptions?
(Note, I want to break on all other CLR exceptions)
I thought DebuggerStepThrough would do the trick. However it doesn't. The following code stops on 'Method1();'
using System;
namespace ConsoleApp8
{
class Program
{
static void Main(string[] args)
{
Method1();
}
[System.Diagnostics.DebuggerStepThrough]
static void Method1()
{
try
{
throw new InvalidOperationException();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
-- Edit --
Kirk - I only throw exceptions in exceptional situations. I work with Visual Studio Tools for Office. This MS library often throws exceptions that can be handled and ignored.
I would like to handle certain exceptions thrown by another library but prevent the VS2017 debugger from stopping when these errors occur.
To be clear, these exceptions are usually COM Exceptions. I don't want the debugger to ignore ALL COM Exceptions. I only want the debugger to ignore COM Exceptions that I have caught and handled.
Is this possible?
The debugger can break execution at the point where an exception is thrown, so you may examine the exception before a handler is invoked. In the Exception Settings window (Debug > Windows > Exception Settings), expand the node for a category of exceptions, such as Common Language Runtime Exceptions. There you can change the behaviour.
Normally I want the debugger to break on ArgumentOutOfRangeException.
But within my try catch(ArgumentOutOfRangeException) that exception is already handled and so I want the debugger to not break.
I tried the DebuggerStepThrough attribute, but it still breaks.
You can do this by setting the debugger to break on user unhandled exceptions.
Go to Debug -> Exceptions, Common Language Runtime Exceptions, de-tick (uncheck) the Thrown box. Of course you can get very precise with what you want to break on by drilling down into that list. Be aware that this setting takes effect across the whole solution, you can't set it per class or method. If you do want to be more selective per method, then consider using compile directives to not include that bit of code during debug time.
As for the DebuggerStepThrough attribute, that is to prevent breaking on break points, nothing to do with breaking on exceptions.
You should check your visual studio isn't set to break on all exceptions
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.
Microsoft Visual Studio Help
There is a way. First disable debugging code that is not yours. Go to Tools > Options > Debugging > General > select "Enable Just My Code (Managed only)". Now tell the debugger that this one function is not part of your code with DebuggerNonUserCodeAttribute:
[System.Diagnostics.DebuggerNonUserCode()]
private void FunctionThatCatchesThrownException()
{
try
{
throw new ArgumentOutOfRangeException();
}
catch (ArgumentOutOfRangeException ex)
{
//...
}
}
If an exception (some other than ArgumentOutOfRangeException) gets out of the function debugger will catch it as usual, but the location of interception will be where the function is called.
When calling a method via methodInfo.Invoke, if an exception is thrown it does not seem to propagate up to my catch blocks.
object value;
try
{
value = myMethod.Invoke(null, parameters);//program crashes with uncaught exception
}
catch
{
throw new Exception("Caught!");//never executed
}
The particular exception this method is raising is KeyNotFoundException, but that shouldn't matter because I'm catching everything right?
The particular error message I get from Visual Studio is
KeyNotFoundException was unhandled by user code
whereas normally the message would say
KeyNotFoundException was unhandled
if the call was not a reflected invocation.
I could just have the method check to see if they key is in there, and if not return null, but Using exception handling seems preferable. Is there any way to propagate exceptions up from a reflected method call?
This could be an issue with the Visual Studio debugger as well. As noted in the accepted answer to this similar question here, there are a few workarounds that you can do. The simplest of which is changing your Visual Studio debugger to turn off "Just My Code" in Tools -> Options -> Debugging -> General. You can also wrap it in a delegate or explicitly try to catch the invocation exception and inspect the inner exception of that, which should be your KeyNotFoundException.
It works for me:
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var method = typeof(Program).GetMethod("ThrowException");
try
{
method.Invoke(null, null);
}
catch (TargetInvocationException e)
{
Console.WriteLine("Caught exception: {0}", e.InnerException);
}
}
public static void ThrowException()
{
throw new Exception("Bang!");
}
}
Note that you do need to catch TargetInvocationException which is the exception thrown directly by Method.Invoke, wrapping the exception thrown by the method itself.
Can you come up with a similar short but complete program which demonstrates the problem?
If an error occurs during a method invoked with reflection, it should throw a TargetInvocationException that wraps (via .InnerException) the original. There are, however, a few methods that could cause more terminal fails, such as a few methods around winform creation / the message loop.
It is also possible that the method is working, but is causing additional work to happen on another thread, and it is that that is failing. This would kill the thread, and you can't catch it as it isn't on your thread. This would be particularly likely if your code is actually on a worker thread.
There has been discussion here before about the correct way to rethrow an exception. This question, instead, is about how to get useful behavior from Visual Studio when using rethrow.
Consider this code:
static void foo() {
throw new Exception("boo!");
}
static void Main(string[] args) {
try {
foo();
} catch (Exception x) {
// do some stuff
throw;
}
}
The exception that comes out has the correct stack trace, showing foo() as the source of the exception. However, the GUI Call Stack window only shows Main, whereas I was expecting it to show the exception's call stack, all the way to foo.
When there is no rethrow, I can use the GUI to very quickly navigate the call stack to see what call caused the exception and how we got there.
With the rethrow I'd like to be able to do the same thing. Instead, the call stack that the GUI shows is of no use to me. I have to copy the exception details to the clipboard, paste it to Notepad, and then manually navigate to whichever function of the call stack I'm interested in.
By the way, I get the same behavior if I add [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] or if I change the catch to just catch (Exception).
My question is: given that the code I have uses rethrow, can someone suggest a convenient way to navigate the call stack associated with the exception? I'm using Visual Studio 2010.
The debugger breaks at the throw in Main because that exception is unhandled. By default, the debugger will only break on unhandled exceptions. Once you've stopped at Main, the call stack for the original exception from foo is present in the exception, but all of the other context has been lost (e.g. locals, stack/memory state).
It sounds like you want the debugger to break on the throw in foo, so you should tell the debugger to break on first-chance exceptions:
Debug ยป Exceptions... (Ctrl+Alt+E)
Check "Thrown" for the exception types you care about (in this case, Commange Language Runtime Exceptions)
Click OK
Start debugging
In this case, the debugger will break immediately when foo throws an exception. Now, you can examine the stack, locals, etc., in the context of the original exception. If you continue execution (F5), the debugger will break again on the rethrow in Main.
Taking another approach, if you're running VS2010 Ultimate, you can also use IntelliTrace to "debug backwards" to see parameters, threads, and variables at the time of the exception. See this MSDN article for details. (Full disclosure: I work on a team closely related to IntelliTrace).
If you use ReSharper, you can copy exception stacktrace to clipboard, then choose in the menu: ReSharper > Tools > Browse Stack Trace (Ctrl+E,T). It will show stacktrace with clickable locations, so you'll be able to quickly navigate.
(source: jetbrains.com)
This feature is also very useful while digging through logs from users (if stacktraces of exceptions are logged).
Not that you should re-throw but here's a blog post about how to preserve the stack trace, essentially it boils down to this:
private static void PreserveStackTrace(Exception exception)
{
MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace",
BindingFlags.Instance | BindingFlags.NonPublic);
preserveStackTrace.Invoke(exception, null);
}
...
catch (Exception ex)
{
// do something
// ...
PreserveStackTrace(ex);
throw;
}
Mike Stall has given a great and simple solution to your problem:
Mark the methods where you rethrow the exception with the attribute [DebuggerNonUserCode]
The IDE will consider this is not your code and will not break the debugger in such place, and instead will look further in the stack, showing the next rethrow or the initial exception place.
(if the next rethrow is also annoying, mark it as [DebuggerNonUserCode] as well, etc...)
Edit: I have looked at the answers code: NONE of them do what I want (I've checked). It would seem that there is no way to do what I want in native c#. I guess that's not a disaster just a shame given that .NET does support it (see accepted answer).
Thanks all.
I have c# code (part of a test framework that will never be run except under a debugger) like this who's point it to avoid actually catching the exception as that makes debugging the code in the unwound part of the stack a royal pain.
Bool bad = true;
try
{
MightThrow();
bad = false;
}
finally
{
if(bad) DoSomeLoggingOnFailure();
//// Does not catch!!!!
//// exception continues to unwind stack.
//// Note that re throwing the exception is NOT
//// the same as not catching it in the first place
}
is their a better way to do this?
A solution would have to behave exactly like that under the debugger with regards to un-caught exceptions. It would have to result in the only one first chance exception and the debugger breaking at the point that the exception was originally thrown, not in a catch block.
Specifically I need the debugger on un-caught exceptions to stop a in side MightThrow.
The following doesn't work because it fails to have the debugger break in the correct place
try { ... } catch { throw; }
And this doesn't work because it loses stack info (and also breaks in the wrong place).
try { ... } catch(Exception e) { throw e; }
I known that in D I could use a scope(failure) block
So, in .NET what you're asking for is theoretically possible, but it's not going to be easy.
CIL actually defines five types of exception handling block! The try, catch and finally ones you're used to in C#, and two others:
filter - similar to a catch block but can run arbitrary code to determine whether it wants to handle the error, rather than just matching on type. This block has access to the exception object, and has the same effect on the exception stack trace as a catch block.
fault - similar to a finally block, however it is only run when an exception occurs. This block does not have access to the exception object, and has no effect on the exception stack trace (just like a finally block).
filter is available in some .NET languages (e.g. VB.NET, C++/CLI) but is not available in C#, unfortunately. However I don't know of any language, other than CIL, that allows the fault block to be expressed.
Because it can be done in IL means not all is lost, though. In theory you could use Reflection.Emit to dynamically emit a function that has a fault block and then pass the code you want to run in as lambda expressions (i.e. one for the try part, one for the fault part, and so on), however (a) this isn't easy, and (b) I'm unconvinced that this will actually give you a more useful stack trace than you're currently getting.
Sorry the answer isn't a "here's how to do it" type thing, but at least now you know! What you're doing now is probably the best approach IMHO.
Note to those saying that the approach used in the question is 'bad practice', it really isn't. When you implement a catch block you're saying "I need to do something with the exception object when an exception occurs" and when you implement a finally you're saying "I don't need the exception object, but I need to do something before the end of the function".
If what you're actually trying to say is "I don't need the exception object, but I need to do something when an exception occurs" then you're half way between the two, i.e. you want a fault block. As this isn't available in C#, you don't have an ideal option, so you may as well choose the option that is less likely to cause bugs by forgetting to re-throw, and which doesn't corrupt the stack trace.
How about this:
try
{
MightThrow();
}
catch
{
DoSomethingOnFailure();
throw; // added based on new information in the original question
}
Really, that's all you did. Finally is for things that must run regardless of whether an exception occurred.
[Edit: Clarification]
Based on the comments you've been mentioning, you want the exception to continue being thrown without modifying its original stack trace. In that case, you want to use the unadorned throw that I've added. This will allow the exception to continue up the stack and still allow you to handle part of the exception. Typical cases might be to close network connections or files.
[Second edit: Regarding your clarification]
Specifically I need the debugger on
un-caught exceptions to stop at the
original point of the throw (in
MightThrow) not in the catch block.
I would argue against ever breaking a best-practice (and yes, this is a best-practice for partially handling exceptions) to add some minor value to your debugging. You can easily inspect the exception to determine the location of the exception throw.
[Final edit: You have your answer]
kronoz has thoughtfully provided you with the answer you sought. Don't break best practices -- use Visual Studio properly! You can set Visual Studio to break exactly when an exception is thrown. Here's official info on the subject.
I was actually unaware of the feature, so go give him the accepted answer. But please, don't go trying to handle exceptions in some funky way just to give yourself a hand debugging. All you do is open yourself up to more bugs.
If you're interested in the debugger simply stopping precisely where the exception occurred then have you considered first-chance exceptions?
If you open Tools|Exceptions then tick the Common Language Runtime Exceptions box, the debugger will stop at the point of exception regardless of any try/catch/finally blocks.
Update: You can specify the precise exception you wish to catch by expanding the [+] tree in the Exceptions dialog. Though of course it will fire every time any exception of the specified type[s] occur[s], you can switch it on and off at will even in the middle of a debugging session, so with judicious use of breakpoints you can get it to do your bidding. I used it successfully to get around the 'target of an invocation has thrown an exception' ball ache originating from using reflection to instantiate objects. Very useful tool in such circumstances. Also note the locals and stack trace should be firmly available as far as I recall (just did a quick test and they are available), so no problems there.
Of course if you want to log things then that is outside the scope of an IDE debugger; and in which case first-chance exceptions won't help you!
Give it a go at least; I found them very useful and they might be more appropriate for your issue than you think.
What's wrong with:
try
{
MightThrow();
}
catch
{
DoSomthingOnFailure();
throw;
}
For code that should only run on exceptions, use the catch block:
try
{
MightThrow();
}
catch (Exception ex)
{
// this runs only when there was an exception
DoSomthingOnFailure();
// pass exception on to caller
throw;
}
finally
{
// this runs everytime
Cleanup();
}
This is what you want. It will only call this method when an error occurs, and the "throw" statement will re-throw the exception with the callstack intact.
try
{
MightThrow();
}
catch
{
DoSomthingOnFailure();
throw;
}
A "finally" block that runs only on failure is called "catch" (with no parameters). :-)
Now, there is a small caveat. If you want to have a specialised "catch" case for a particular exception type and have a generic "catch" that works for all exceptions, you'll have to do a bit of a custom logic.
Thus, I would do something like:
try
{
MightThrow();
}
catch(MyException ex)
{
// Runs on MyException
MySpecificFailureHandler()
// Since we have handled the exception and can't execute the generic
// "catch" block below, we need to explicitly run the generic failure handler
MyGenericFailureHandler()
}
catch
{
// Runs on any exception hot handled specifically before
MyGenericFailureHandler()
// If you want to mimic "finally" behavior and propagate the exception
// up the call stack
throw;
}
finally
{
// Runs on any failure or success
MyGenericCleanupHandler();
}
Every example so far is losing the original StackTrace according to my tests. Here's a solution that should work for you.
private static void PreserveStackTrace(Exception exception)
{
MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace",
BindingFlags.Instance | BindingFlags.NonPublic);
preserveStackTrace.Invoke(exception, null);
}
try
{
MightThrow();
}
catch (Exception ex)
{
DoSomethingOnFailure();
PreserveStackTrace(ex);
throw;
}
How about only catching an exception that "MightThrow" does not throw?
Bool bad = true;
try
{
MightThrow();
bad = false;
}
catch (SomePrivateMadeUpException foo)
{
//empty
}
finally
{
if(bad) DoSomeLoggingOnFailure();
}
Let me recap your requirements the way I understand them:
You want some code that is run only when an exception is generated, in order to do some logging.
You want to run your test framework under debugger and break at the point at which the exception is thrown.
To meet your first requirement, you should write the code the way everybody suggested - using parameterless catch and throw.
To meet your second requirement while using the parameterless catch, you could configure your debugger to break when an exception is throw, not only when there's an unhandled exception. I suspect you know how to do it, but I'll put it here for answer completeness: in VS you can do that in Debug -> Exception -> Common Language Runtime Exceptions -> check the Thrown checkbox.
If you know that your app throws a lot of handled exceptions, that might not be an option for you. At that point, your only choice left to meet your first requirement is to either write the code to use finally for exception logging purposes or look into the direct IL emitting route as Greg Beech suggests.
However, whether the finally code is being executed depends on the debugger you are using. In particular, VS will break on an unhadled exception before the finally is executed and will not let you continue. Thus, unless you detach from the process at that point, your logging code will never be executed. In other words, the second requirement will interfere with meeting the first requirement.
You could encapsulate your logic in a custom class, something like:
public class Executor
{
private readonly Action mainActionDelegate;
private readonly Action onFaultDelegate;
public Executor(Action mainAction, Action onFault)
{
mainActionDelegate = mainAction;
onFaultDelegate = onFault;
}
public void Run()
{
bool bad = true;
try
{
mainActionDelegate();
bad = false;
}
finally
{
if(bad)
{
onFaultDelegate();
}
}
}
}
And use it as:
new Executor(MightThrow, DoSomeLoggingOnFailure).Run();
Hope this helps.
Isn't this the same as:
try
{
MightThrow();
}
catch (Exception e)
{
DoSomethingOnFailure();
throw e;
}
?
You could write, or have someone write for you, a small assembly in VB.net which implements a TryFaultCatchFinally(of T) method that accepts four delegates:
TryMethod -- An Action(of T) to perform the "Try" block.
FaultMethod -- A Predicate(Of T, Exception) which, if an exception occurs, will be called before any "finally" blocks run; if it returns true the Catch block will run--otherwise it won't.
CatchMethod -- An Action(Of T, Exception) to be performed if an exception had occurred and FaultMethod returned true; happens after "finally" blocks run.
FinallyMethod -- An Action(OF T, Exception, Boolean) to be performed as a "Finally" block. The passed-in exception will be null if TryMethod ran to completion, or will hold the exception that caused it to exit. The Boolean will be true if the exception was caught, or false otherwise.
Note that when the FaultMethod is executed, one may be able to examine the state of objects that caused the exception, before such state is destroyed by Finally blocks. One must use some care when doing this (any locks that were held when the exception was thrown will continue to be held) but the ability may still sometimes be handy, especially when debugging.
I'd suggest the routine look something like:
Shared Sub TryFaultCatchFinally(Of T)(ByVal TryProc As Action(Of T), _
ByVal FaultProc As Func(Of T, Exception, Boolean), _
ByVal CatchProc As Action(Of T, Exception), _
ByVal FinallyProc As Action(Of T, Exception, Boolean), _
ByVal Value As T)
Dim theException As Exception = Nothing
Dim exceptionCaught As Boolean = False
Try
TryProc(Value)
theException = Nothing
exceptionCaught = False
Catch Ex As Exception When CopyExceptionAndReturnFalse(Ex, theException) OrElse FaultProc(Value, Ex)
exceptionCaught = True
CatchProc(Value, Ex)
Finally
FinallyProc(Value, theException, exceptionCaught)
End Try
End Sub
No, I think this is a common idiom the way you have it.
EDIT
To be clear, the "catch" then "rethrow" strategies offer the same run-time semantics, however they change the experience when the VS debugger is attached. Tooling and maintenance is important; debugging often requires you to 'catch all first-chance exceptions' and if you end up with lots of 'spurious' first-chance exceptions due to catch-then-rethrow in your code, it really hurts the ability to debug the code. This idiom is about interacting well with the tooling, as well as clearly expressing the intent (you don't want to 'catch', decide can't handle, and rethrow, instead you just want to log that an exception did happen but let it pass on by).
Have you considered using the DebuggerStepThrough attribute?
http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx
[DebuggerStepThrough]
internal void MyHelper(Action someCallback)
{
try
{
someCallback();
}
catch(Exception ex)
{
// Debugger will not break here
// because of the DebuggerStepThrough attribute
DoSomething(ex);
throw;
}
}
With exception filters added in C# 6, one option is to make use of a false returning exception filter, like so:
void PerformMightThrowWithExceptionLogging()
{
try
{
MightThrow();
}
catch (Exception e) when (Log(e))
{
// Cannot enter here, since Log returns false.
}
}
bool Log(Exception e)
{
DoSomeLoggingOnFailure(e);
// Return false so the exception filter is not matched, and therefore the stack is kept.
// This means the debugger breaks where the exception actually happened, etc.
return false;
}
See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch for more details on exception filters.
try
{
MightThrow();
}
catch
{
DoSomethingOnFailure();
}