We have UnhandledExceptionEventHandler in place and unexpected exceptions were caught by that handler. But why we still see the following screen? I thought if we handled the exception, it will not go up to the OS. If no exception reach the system level, why that screen still show up?
Registering an UnhandledExceptionEventHandler with AppDomain.UnhandledException does not mean that unhandled exceptions become handled. Instead, it is a mechanism to be able to log the exception and relevant program state to aid in later debugging. The exception will remain unhandled and Windows Error Reporting will be invoked.
In reality, when this event is invoked it's "too late" for the the exception to be handled. Assuming you could tell the runtime to continue execution, where would execution unwind to? Not a single frame on the call stack wanted to handle the exception. At best, the executing thread could be terminated; but what if it's on the only foreground thread? Better to propagate the unhandled exception to the operating system's default unhandled exception filter and let it invoke Windows Error Reporting.
Edit with some additional comments:
Now, certain applications you want to design to be crash-resistant, such as long-running service processes. It may make sense to add "catch-all"* exception handlers in some cases, such as a job queue that executes jobs and it doesn't matter if an individual job fails with an unhandled exception; we log the problem and move on to the next job. However, a root catch-all handler in something like Main makes little sense: your entire application is now in an unknown state. You could log the exception and terminate, but you'd be missing out on the benefits of Windows Error Reporting: post-mortem minidumps and an easy button (the "Debug" button on that dialog) to invoke the registered JIT debugger that will take you directly to the problem. For most software, my advice is to simply let your software crash; in-your-face bugs with minidumps are usually some of the easiest to fix.
*Some exceptions are inherently "uncatchable", such as a StackOverflowException. Others, such as an AccessViolationException are catchable, but are inherently indicative of a serious program state incongruity (couldn't read or write from an expected memory location). It is never a good idea to attempt recovery from such exceptions.
Click the Debug button to see where the exception comes from.
If you don't see it immediately, start your application in Visual Studio, go to the Debug,Exceptions dialog, and check all exceptions. Then rerun your application, investigate the code every time the debugger tells you that a first-chance exception has been encountered, and pass the exception to the application if Visual Studio asks you whether to do this.
This should help you finding the source of the problem.
That's because your unhandled exception occurs in the main thread, and there is almost nothing to do about it. Check this article: What!? A .NET Application Can Die?
Almost nothing, yes, because you can still catch that exception on the Application.Run level. At this point your application is dead anyway, but at least you can "avoid windows crash screen" and implement your own crash screen instead:
static void Main()
{
try
{
Application.Run(new Form1());
}
catch (Exception ex)
{
MessageBox.Show("Oops! Can I has " + ex.Message + "?");
}
}
There are cases when unhadled exceptions will not be handled by UnhandledExceptionEventHandler. For example System.Timers.Timer is swallowing exceptions, so they are not propagated to UnhandledExceptionEventHandler.
Related
I have been asked to add error logging to an application that logs whenever an exception is thrown.
I have a method which will perform the log and I could call this in every Catch clause.
This seems daft as there are literally hundreds of try catch statements in the app.
In visual studio you can set the IDE to break after every exception regardless of try catches, so I am wondering if this sort of functionality is possible to use (albeit not breakpointing the code when thrown)
in summary my question is:
Is there a way to fire an event (or similar) that would call this method, whenever a custom or CLR exception is thrown.
as a bonus question related to this, is it possible to do similar with method entry / exit logging?
C#
.Net 4.5
VS 2012
If you want your function to be called just like how Visual Studio would break on a first chance exception (breaks on a throw even inside a try-catch block) then you need to subscribe to the FirstChanceExecption event in the AppDomain you are running in.
AppDomain.CurrentDomain.FirstChanceException += YourLoggingFunction;
You need to do this for every AppDomain in your program, but unless you are doing non-common tasks 99% of all programs will likely only ever have a single AppDomain
See this MSDN page for more information about subscribing to other AppDomains if you are using them.
Be aware, you may get more exceptions than you realize, some .NET framework code throws exceptions internally and just have the code in try-catch blocks so it never comes up to the surface1 or if the library code has the pattern
try
{
SomeFunctionThatThrows()
}
catch (Exception innerException)
{
throw new SomeMoreDetailedException(message, stateDetails, innerException);
}
subscribing to the event will cause you to start seeing both the exception thrown from SomeFunctionThatThrows() and from throw new SomeMoreDetailedException(2.
1: This is most common in network based I/O calls where an exception like a TimeoutException would be common but the end user does need to know a timeout error happened as there may be things like internal retry logic that happens before the user is notified.
2: You could also see them in Visual Studio by disabling "Just My Code" and breaking on all thrown exceptions.
If I put AppDomain.CurrentDomain.UnhandledException code in console application apart from usual try-catch to catch unhandled exceptions. That means, is it sure that any exception will not force application to terminate in between?
If not, what type of exceptions are out of scope of it?
No. It means that you will have the chance to run some code before your application crashes, but you will not be able to prevent the crash. Documentation:
This event provides notification of uncaught exceptions. It allows the
application to log information about the exception before the system
default handler reports the exception to the user and terminates the
application.
Trying to make the application "crash-proof" by blindly catching all exceptions is a fool's errand: since you don't really know what went wrong, how do you know that it's OK for the program to continue running?
Theoretically speaking, anything you do inside the event handler might go wrong in any possible manner (since an unhandled exception was thrown, and you don't know what it is, it could be anything). So not only is it impossible to prevent the application from crashing, but you should also be very careful about what you do inside the handler.
No, the application will be terminated anyway, but it gives you a chance to log the exception properly before the application exits. See here: http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx
It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.
I have a console application written in C#/.NET that I want to run from a script (nant). If an exception occurs in the console application, I would like nant to continue, but in Windows Vista there is a popup that searches for solutions and asks for debug etc.
I would like to avoid the popup with "program stopped working" when an exception happens in the console application. How can I control this from C#/.NET?
(A similar question addresses the issue for the C language, but I would like a solution for C#/.NET.)
(To clarify: I would like the exception to be passed to nant, but without the popup.)
The JIT debugger popup occurs when there's an unhandled exception. That is, an exception tunnels all the way up the stack to the root of any thread in the runtime.
To avoid this, you can handle the AppDomain.CurrentDomain.UnhandledException event and just call Environment.Exit(1) to exit gracefully.
This will handle all exceptions on all threads within your AppDomain. Unless you're doing anything special, your app probably only has one AppDomain, so putting this in your public static void Main method should suffice:
AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
Console.Error.WriteLine("Unhandled exception: " + args.ExceptionObject);
Environment.Exit(1);
};
You should probably use the NAnt logger to write out the error in this case too (can't recall the API for this offhand though.)
You can also disable JIT debugging on the machine. I would only recommend this in certain circumstances such as for a dedicated build server.
Under Windows Vista you can disable this dialog for your programms.
Disable the "Problem Reports and Solutions feature". You find it under Control Panel-->Problem Reports and Solutions-->Change Settings-->Advanced Settings-->Turn off for my programs, problem reporting
Just catch the exception and log/ignore it.
The popup appears due to an unhandled exception. To avoid that make sure your main method captures all exceptions and turn them into some other useful piece of info you can pick up. Just ignoring the exception is not recommended.
Btw remember that exceptions are per thread, so if your application spawns threads or uses thread pool threads, you need a handler for these too.
Usually this only happens when your app doesnt handle an exception. If you wrap your whole console app in a try/catch bblock, and just pass back a fail code, then you will avoid this.
Sometimes, a windows application will stop working if you are using a System.Timers.Timer.
To fix this, change System.Timers.Timer by System.Windows.Forms.Timer
Greetings
In several places in our code, we notice that if running under debugger it'll show that there's an unhandled exception in the code, however if running outside the debugger it will just ignore the exception completely as if it were caught. We have an exception handler that pops up an error submit dialog that's hooked up to Application.ThreadException and AppDomain.CurrentDomain.UnhandledException
And neither of those appear to be catching them either. We also log our exceptions and nothing appears in the log.
What are some possible reasons for this?
Edit: It seems that it isn't dependent on the type of exception throw, but rather where it is thrown. This was tested by just adding:
throw new Exception("Test Exception");
It'll show up under debugger but doesn't show up outside, so in our case it's not a ThreadAbortedException or anything that's dependent on it being a specific type of exception.
There are some special exceptions that don't get bubbled up or caught, it sounds like you're dealing with one of them: see ThreadAbortException
Found one place where this could occur is if there's an exception in the UnhandledException event handler. An easy way to see this is this:
In the Form.Load event handler throw any old exception.
In the Application.ThreadException event put something similar to the following:
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
string b = null;
int i = b.Length;
}
Under debugger it'll show your exception was unhandled by user code, and then after that it'll show a null reference exception in the ThreadException handler, but if you run it outside the debugger it'll just swallow the exception like it was handled.
If you try to modify the properties of a Windows Form control from a different thread the control was created in, you get an InvalidOperationException if there is a debugger attached, but it gets silently ignored otherwise.
More info on the issue can be found here:
http://msdn.microsoft.com/en-us/library/ms171728(VS.80).aspx
Your code is invoked from the framework.
Sometimes, the framework wraps its calls in an exception handler.
So, if there's an exception in your code, it may be (if there's an exception handler there in the framework) caught and ignored by the framework.
Maybe the debugger shows it as "unhandled" because, although there's a handler in the framework, there's no handler in your code? Or, because there's something strange about the handler in the framework, for example that it's an unmanaged, structured exception handler?
Are you using .Net 1.0/1.1? There was a huge change in behaviour in the transition from 1.1 to 2.0. Before then exceptions raised on threads you created or ThreadPool threads would be swallowed silently by the frameworok and the thread would exit. Thankfully this behaviour has now been fixed.
From MSDN:
Change from Previous Versions
The most significant change pertains
to managed threads. In the .NET
Framework versions 1.0 and 1.1, the
common language runtime provides a
backstop for unhandled exceptions in
the following situations:
There is no such thing as an unhandled
exception on a thread pool thread.
When a task throws an exception that
it does not handle, the runtime prints
the exception stack trace to the
console and then returns the thread to
the thread pool.
There is no such thing as an unhandled
exception on a thread created with the
Start method of the Thread class. When
code running on such a thread throws
an exception that it does not handle,
the runtime prints the exception stack
trace to the console and then
gracefully terminates the thread.
There is no such thing as an unhandled
exception on the finalizer thread.
When a finalizer throws an exception
that it does not handle, the runtime
prints the exception stack trace to
the console and then allows the
finalizer thread to resume running
finalizers.
Kind of a stretch here, but could it be that you just have set your debugger to break when an exception is thrown, and not only for the unhandled ones?
I'm maintaining a .NET 1.1 application and one of the things I've been tasked with is making sure the user doesn't see any unfriendly error notifications.
I've added handlers to Application.ThreadException and AppDomain.CurrentDomain.UnhandledException, which do get called. My problem is that the standard CLR error dialog is still displayed (before the exception handler is called).
Jeff talks about this problem on his blog here and here. But there's no solution. So what is the standard way in .NET 1.1 to handle uncaught exceptions and display a friendly dialog box?
Jeff's response was marked as the correct answer because the link he provided has the most complete information on how to do what's required.
Oh, in Windows Forms you definitely should be able to get it to work. The only thing you have to watch out for is things happening on different threads.
I have an old Code Project article here which should help:
User Friendly Exception Handling
Unhandled exception behavior in a .NET 1.x Windows Forms application depends on:
The type of thread that threw the exception
Whether it occurred during window message processing
Whether a debugger was attached to the process
The DbgJitDebugLaunchSetting registry setting
The jitDebugging flag in App.Config
Whether you overrode the Windows Forms exception handler
Whether you handled the CLR’s exception event
The phase of the moon
The default behavior of unhandled exceptions is:
If the exception occurs on the main thread when pumping window messages, it's intercepted by the Windows Forms exception handler.
If the exception occurs on the main thread when pumping window messages, it will terminate the app process unless it's intercepted by the Windows Forms exception handler.
If the exception occurs on a manual, thread-pool, or finalizer thread, it's swallowed by the CLR.
The points of contact for an unhandled exception are:
Windows Forms exception handler.
The JIT-debug registry switch DbgJitDebugLaunchSetting.
The CLR unhandled exception event.
The Windows Form built-in exception handling does the following by default:
Catches an unhandled exception when:
exception is on main thread and no debugger attached.
exception occurs during window message processing.
jitDebugging = false in App.Config.
Shows dialog to user and prevents app termination.
You can disable the latter behavior by setting jitDebugging = true in App.Config. But remember that this may be your last chance to stop app termination. So the next step to catch an unhandled exception is registering for event Application.ThreadException, e.g.:
Application.ThreadException += new
Threading.ThreadExceptionHandler(CatchFormsExceptions);
Note the registry setting DbgJitDebugLaunchSetting under HKEY_LOCAL_MACHINE\Software.NetFramework. This has one of three values of which I'm aware:
0: shows user dialog asking "debug or terminate".
1: lets exception through for CLR to deal with.
2: launches debugger specified in DbgManagedDebugger registry key.
In Visual Studio, go to menu Tools → Options → Debugging → JIT to set this key to 0 or 2. But a value of 1 is usually best on an end-user's machine. Note that this registry key is acted on before the CLR unhandled exception event.
This last event is your last chance to log an unhandled exception. It's triggered before your Finally blocks have executed. You can intercept this event as follows:
AppDomain.CurrentDomain.UnhandledException += new
System.UnhandledExceptionEventHandler(CatchClrExceptions);
AppDomain.UnhandledException is an event, not a global exception handler. This means, by the time it is raised, your application is already on its way down the drain, and there is nothing you can do about it, except for doing cleanup and error logging.
What happened behind the scenes is this: The framework detected the exception, walked up the call stack to the very top, found no handlers that would recover from the error, so was unable to determine if it was safe to continue execution. So, it started the shutdown sequence and fired up this event as a courtesy to you so you can pay your respects to your already-doomed process. This happens when an exception is left unhandled in the main thread.
There is no single-point solution to this kind of error. You need to put a real exception handler (a catch block) upstream of all places where this error occurs and forward it to (for example) a global handler method/class that will determine if it is safe to simply report and continue, based on exception type and/or content.
Edit: It is possible to disable (=hack) the error-reporting mechanism built into Windows so the mandatory "crash and burn" dialog does not get displayed when your app goes down. However, this becomes effective for all the applications in the system, not just your own.
Is this a console application or a Windows Forms application? If it's a .NET 1.1 console application this is, sadly, by design -- it's confirmed by an MSFT dev in the second blog post you referenced:
BTW, on my 1.1 machine the example from MSDN does have the expected output; it's just that the second line doesn't show up until after you've attached a debugger (or not). In v2 we've flipped things around so that the UnhandledException event fires before the debugger attaches, which seems to be what most people expect.
It sounds like .NET 2.0 does this better (thank goodness), but honestly, I never had time to go back and check.
It's a Windows Forms application. The exceptions that are caught by Application.ThreadException work fine, and I don't get the ugly .NET exception box (OK to terminate, Cancel to debug? who came up with that??).
I was getting some exceptions that weren't being caught by that and ended up going to the AppDomain.UnhandledException event that were causing problems. I think I've caught most of those exceptions, and I am displaying them in our nice error box now.
So I'll just have to hope there are not some other circumstances that would cause exceptions to not be caught by the Application.ThreadException handler.
The Short Answer,
Looks like, an exception occurring in Form.Load doesn't get routed to Application.ThreadException or AppDomain.CurrentDomain.UnhandledException without a debugger attached.
The More accurate Answer/Story
This is how I solved a similar problem. I can't say for sure how it does it, but here is what I think. Improvement suggestions are welcome.
The three events,
AppDomain.CurrentDomain.FirstChanceException
AppDomain.CurrentDomain.UnhandledException
and Application.ThreadException
accumulatively catch most of the exceptions but not on a global scope (as said earlier). In one of my applications, I used a combination of these to catch all kinds of exceptions and even the unmanaged code exceptions like DirectX exception (through SharpDX). All exceptions, whether they are caught or not, seem to be invoking FirstChanceException without a doubt.
AppDomain.CurrentDomain.FirstChanceException += MyFirstChanceExceptionHandler;
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); // not sure if this is important or not.
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // can't use Lambda here. need to Unsub this event later.
Application.ThreadException += (s, e) => MyUnhandledExceptionHandler(e.Exception);
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MyUnhandledExceptionHandler((Exception)e.ExceptionObject);
}
private void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs eventArgs)
{
// detect the pattern of the exception which we won't be able to get in Fatal events.
if (eventArgs.Exception.Message.StartsWith("HRESULT"))
MyUnhandledExceptionHandler(eventArgs.Exception);
}
and the handler looks like
static void MyUnhandledExceptionHandler(Exception ex)
{
AppDomain.CurrentDomain.UnhandledException -= MyUnhandledExceptionHandler; // this is important. Any exception occuring in the logging mechanism can cause a stack overflow exception which triggers the window's own JIT message/App crash message if Win JIT is not available.
// LogTheException()
// Collect user data
// inform the user in a civil way to restart/close the app
Environment.Exit(0);
}
Unmanaged code exceptions like DirectX exceptions appeared only in FirstChanceException where I had to decide for myself if the exception was fatal or not. I then use MyUnhandledExceptionHandler to log and let the user know in a friendly way that everything was "under control".
IMPORTANT NOTE!
The scheme still didn't catch one kind of exception. It did appear in FirstChanceException, but it was hard to distinguish it from other kinds of exceptions hitting this handler. Any exception occurring directly in Form.Load had this different behavior. When the VS debugger was attached, these were routed to the UnhandledException event. But without a debugger, an old-school windows message will pop up, showing the stack trace of the exception that occurred. The most annoying thing was that it didn't let MyUnhandledExceptionHandlerr get kicked once it was done and the app continued to work in an abnormal state. The final solution I did was to move all the code from Form_load to another thread using MyForm.Load += (s,e) => new Thread(()=>{/* My Form_Load code*/ }).Start();. This way, Application.ThreadException gets triggered which is routed to MyUnhandledExceptionHandler, my safe exit.