When debugging a C# program with Visual Studio, how can you see if the code you're stepping through is in a try/catch block?
That is, if the code throws an exception, will the exception be caught by another part of the program or not?
The problem is that there's an application which is prone to crashing when used out in the wild, but we can't replicate the problem here under the debugger, and we think that all exceptions are caught, but apparently we're wrong!
And it's a large program, with lots of classes and event handlers and timers, so it's not always straightforward in which order things are executed.
So, how can you tell which parts of a program have potential uncaught exceptions, other than stepping up through the call stack constantly to see if you find a try?
You may need AppDomain.UnhandledException
Related
Whenever I have a try/catch statement in my own code, the Exception still breaks to debugger.
I can turn off the check Break when this exception type is
thrown.
I don't want to do that because I do want to break in all other cases that I don't have a try/catch.
I can turn Except when thrown from this dll. I don't want to that for the exact same reason. There are valid reasons in that DLL why I want to break when I do not try/catch it myself.
I just want to not break when I have a try/catch statement, because I am already handling it so I don't want to be bugged by every external call that is failing.
How can I do this?
UPDATE
This mainly seems to be a problem with ASP.NET. Probably because there is one big try/catch per request in the outermost ASP.NET layer.
So what I'm looking for in a way is something like:
Break only try/catched in external code.
Maybe I don't understand your question but if you just take out "Break when this exception type is thrown" you should have the exact behaviour you want. The debugger will still break if the exception isn't caught. The only thing this checkbox does is tell the debugger to break even if the exception got caught.
If this is not the behaviour you want I may need some clarification to understand your question.
Edit:
Since you've now edited your question and you seem to be looking for "Break only try/catched in external code.", I can only tell you that I wouldn't know of such a feature and have never used anything like that. That does not mean it doesn't exist though.
I wrote a console application that uses Socket's *Async set of methods and it crashes time to time. It doesn't show me where it threw the exception like synchronized code, console just shuts down and I have no idea what have I done wrong.
Is there a way to detect exceptions when it comes to asynchronous operations like this without knowing where to put a try/catch block?
All I need is to know what part of the code makes my application crash.
Edit:
The usual thing with the unhandled exceptions is when you are debugging your code using Visual Studio, it pauses the execution and shows you the line of code that caused the exception (or at least the exception message). But in some situations (e.g. interacting with a low level API like IOCP) your program just crashes and debugging ends with no information about its cause.
What I need is a way to see that particular exception:
"What happened or where (in which method) it happened so my program crashed?"
So I don't ask "What have I done wrong?", I ask "How can I find out what have I done wrong?"
Can I make the execution break at the point where the exception is thrown?
Can I see the call stack after crash to identify the method that caused it?
Could you provide any advice to avoid these kind of situations?
Click Debug-menu -> Exceptions. Make sure Common Language Runtime Exceptions are thrown. Sometimes the IDE unchecks this option. I don't know why, but it's annoying.
Enable System.Net logging to see whats happening underneath
What happens in a C# program if an exception is not caught. Does the program 'crash' with something like a run-time error?
What happens in a C# program if an exception is not caught. Does the program 'crash' with something like a run-time error?
Maybe.
Maybe not.
What happens is implementation-defined.
For example, you might get a dialog box that says "there was an unhandled exception, and I see you have Visual Studio installed. Do you want to start up the debugger and examine the program state?"
You might get a dialog box that says "there was an unhandled exception, do you want to report this to Microsoft?"
If you are already running in the debugger, the debugger probably does something to bring it to your attention.
The runtime is allowed to do whatever it wants, and that includes asking you what to do.
Note that the runtime is aware of whether there's going to be a catch block or not before the finally blocks run. You can easily demonstrate this with a console app. Write an app that crashes, and outputs in the finally block:
Unhandled Exception: System.Exception: Exception of type
'System.Exception' was thrown at
ConsoleApplication1.Program.Main(String[] args)
finally running now
See what happens? The runtime reports the error, gives the debugger a chance to run, or reports the problem to Microsoft, or whatever, before it runs the finally blocks. If they run at all. They might not. Anything can happen. The user could decide to destroy the process, or start a debugger and fix the exception, or whatever.
If you really want to understand how exceptions work in C# you should read this:
http://blogs.msdn.com/b/cbrumme/archive/2003/10/01/51524.aspx
Yes.
Yes.
Something "exceptional" has happened, and your program does not know how to handle it, so it must stop execution at that point and "crash". There will be code that is executed after the crash, such as finally blocks, but basically the party is over for your code.
The best thing to do is to log these events, giving as much intofmation about the state of the system/program at the time of the crash. The Logging Application Block is one of the more robust automatic ways to log errors.
Try it! Depending on the error, it will usually catch. Now, as for should all exceptions be caught, if its something like a[i] where it COULD throw an error if i is too big, but you knew that i was supposed to be kept within bounds (for example, in a for loop), you would not catch that exception.
However, if you are using data coming from a user (say, from a GUI) you would almost always validate it.
Try it yourself!
class Program
{
static void Main(string[] args)
{
int[] arr = new int[1];
arr[5] = 6; //throws an exception; what kind?
}
}
Compile and run this in debug mode for a quick answer to your question.
Or just write some programs. Sooner or later, your code will throw exceptions; it happens to all of us, usually more times than we can count. In console or WinForms applications, an unhandled exception will usually crash the program; in ASP.NET, it will generate an error page, but it won't crash the whole website. You can also write custom code that specifies what to do in case of an unhandled exception, so that your application will fail gracefully.
I have a strange scenario when my application can get into an infinite loop when shutting down. It occurs when it wants to do something but the calls fail as it no longer has access (time based). In such a scenario it should just stop.
I record failed attempts and if the count goes above a certain number in a certain time I throw an exception which I expect to start the JIT debugger and stop the application.
I am not entirely sure why it gets into the loop so I want the JIT window that gives me information like the call stack and application status.
I have exception handling, but what I want is to turn it off and somehow generate an exception that will trigger the JIT debugger, however, all other posts I have found have been for handling exceptions and avoid crashes.
If there is another way at runtime to have the application stop and tell me what is happening I would like to know.
Thanks.
You should try Debugger.Launch() and Debugger.Break() methods (but remember that you should use them only in development environment). You can read more here: http://msdn.microsoft.com/en-us/library/7kzs2ysh.aspx
This line:
System.Diagnostics.Debugger.Launch();
will launch the debugger for you. Give it a try.
I have exception handling
Sounds to me that you have too much of it. Only ever catch specific exception types, never catch Exception. Now you can simply throw any other exception type and your app will bomb with an unhandled exception. Which brings up the JIT debugger dialog on your dev machine, a merciful end on your customer's machine.
Using System.Diagnostics.Debugger is good too, but wrap it with #ifdef DEBUG. Your customer doesn't have one.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
.NET - What’s the best way to implement a “catch all exceptions handler”
I have a .NET console app app that is crashing and displaying a message to the user.
All of my code is in a try{<code>} catch(Exception e){<stuff>} block, but still errors are occasionally displayed.
In a Win32 app, you can capture all possible exceptions/crashes by installing various exception handlers:
/* C++ exc handlers */
_set_se_translator
SetUnhandledExceptionFilter
_set_purecall_handler
set_terminate
set_unexpected
_set_invalid_parameter_handler
What is the equivalent in the .NET world so I can handle/log/quiet all possible error cases?
You can add an event handler to AppDomain.UnhandledException event, and it'll be called when a exception is thrown and not caught.
Contrary to what some others have posted, there's nothing wrong catching all exceptions. The important thing is to handle them all appropriately. If you have a stack overflow or out of memory condition, the app should shut down for them. Also, keep in mind that OOM conditions can prevent your exception handler from running correctly. For example, if your exception handler displays a dialog with the exception message, if you're out of memory, there may not be enough left for the dialog display. Best to log it and shut down immediately.
As others mentioned, there are the UnhandledException and ThreadException events that you can handle to collection exceptions that might otherwise get missed. Then simply throw an exception handler around your main loop (assuming a winforms app).
Also, you should be aware that OutOfMemoryExceptions aren't always thrown for out of memory conditions. An OOM condition can trigger all sorts of exceptions, in your code, or in the framework, that don't necessarily have anything to do with the fact that the real underlying condition is out of memory. I've frequently seen InvalidOperationException or ArgumentException when the underlying cause is actually out of memory.
This article in codeproject by our host Jeff Atwood is what you need.
Includes the code to catch unhandled exceptions and best pratices for showing information about the crash to the user.
The Global.asax class is your last line of defense.
Look at:
protected void Application_Error(Object sender, EventArgs e)
method
Be aware that some exception are dangerous to catch - or mostly uncatchable,
OutOfMemoryException: anything you do in the catch handler might allocate memory (in the managed or unmanaged side of the CLR) and thus trigger another OOM
StackOverflowException: depending whether the CLR detected it sufficiently early, you might get notified. Worst case scenario, it simply kills the process.
You can use the AppDomain.CurrentDomain.UnhandledException to get an event.
Although catching all exceptions without the plan to properly handle them is surely a bad practice, I think that an application should fail in some graceful way. A crash should not scare the user to death, and at least it should display a description of the error, some information to report to the tech support stuff, and ideally a button to close the application and restart it. In an ideal world, the application should be able to dump on disk the user data, and then try to recover it (but I see that this is asking too much).
Anyway, I usually use:
AppDomain.CurrentDomain.UnhandledException
You may also go with Application.ThreadException Event.
Once I was developing a .NET app running inside a COM based application; this event was the very useful, as AppDomain.CurrentDomain.UnhandledException didn't work in this case.
I think you should rather not even catch all Exception but better let them be shown to the user. The reason for this is that you should only catch Exceptions which you can actually handle. If you run into some Exception which causes the program to stop but still catch it, this might cause much more severe problems.
Also read FAQ: Why does FxCop warn against catch(Exception)?.
Be aware that catching these unhandled exceptions can change the security requirements of your application. Your application may stop running correctly under certain contexts (when run from a network share, etc.). Be sure to test thoroughly.
it doesn't hurt to use both
AppDomain.CurrentDomain.UnhandledException
Application.ThreadException
but keep in mind that exceptions on secondary threads are not caught by these handlers; use SafeThread for secondary threads if needed