I've a C# WPF application that throws following error message and crashes:
System.AccessViolationException: Attempted to read or write protected
memory. This is often an indication that other memory is corrupt.
I then added following exception handlers in the code. And also added following line of code in the start of the method which was throwing above exception.
throw new System.AccessViolationException();
Exception handlers are now getting executed on clicking the app exe on my local machine when above exception occurs, but the app still crashes. I need to be able to prevent the app from crashing. Not sure how do I do that?
application.DispatcherUnhandledException += ApplicationDispatcherUnhandledException;
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
AppDomain currentAppDomain = AppDomain.CurrentDomain;
currentAppDomain.UnhandledException += new UnhandledExceptionEventHandler
(UnhandledExceptionHandler);
Thanks.
You need to identify what part of code is throwing that exception. I bet it is some external unmanged library.
If you cannot repair that library, you can follow instructions on MSDN:
AccessViolationException
AccessViolationException and try/catch blocks
Starting with the .NET Framework 4, AccessViolationException
exceptions thrown by the common language runtime are not handled by
the catch statement in a structured exception handler if the exception
occurs outside of the memory reserved by the common language runtime.
To handle such an AccessViolationException exception, you should apply
the HandleProcessCorruptedStateExceptionsAttribute attribute to the
method in which the exception is thrown. This change does not affect
AccessViolationException exceptions thrown by user code, which can
continue to be caught by a catch statement. For code written for
previous versions of the .NET Framework that you want to recompile and
run without modification on the .NET Framework 4, you can add the
element to your app's
configuration file. Note that you can also receive notification of the
exceptions if you have defined a handler for the
AppDomain.FirstChanceException or AppDomain.UnhandledException event.
Related
In my windows C#.net application, using some third party libraries which are of c++. and in few cases, I am unable to catch the exceptions thrown from those c++ libraries, I have tried all the below global exception handlers, but still unable to catch the exception.
AppDomain.CurrentDomain.UnhandledException
OnUnobservedTaskException
Current.DispatcherUnhandledException
Dispatcher.UnhandledException
Current.Dispatcher.UnhandledExceptionFilter
System.Windows.Forms.Application.ThreadException
The application is getting crashed with out any information logged in file, but putting an entry in Event viewer with application error like below:
Faulting module name: ucrtbase.dll, version: 10.0.19041.789, time
stamp: 0x82dc99a2
Exception code: 0xc0000409
Also tried Marking the RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true) in the AssmblyInfo file.
<legacyCorruptedStateExceptionsPolicy enabled="true" /> in App.config file.
And Decorate the method with the HandleProcessCorruptedStateExceptions attribute
Also tried inline with the method which is calling third part method causing exception by placing Empty catch block
still unable to catch native exceptions.
I have so many calls for third party methods in many places, so I am not sure to handle all of them with Try catch. So I need a global handler to log the exception but not crash the application.
My requirement here is to catch the native exceptions globally and log to my log file with out adding entry in event viewer.
I'm debugging and enhancing a C#/XAML program that repeatedly generates an exception while running which I can see looking at the Output window.
A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll
A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll
(for some reason they seem to happen in pairs) The program itself keeps running after the exceptions occur.
The program consists of some XAML/C# code-behind which forms a front-end and test harness for a library of calls in a .Net DLL, which is also part of our C# code.
The total code-base (front end and DLL) is about 100K lines of C# source code code spread among about 25 files. It mostly runs in one thread except for code which runs in socket-data handlers which get called by the system when data arrives from outside hardware devices (this program runs a factory manufacturing process).
How do I narrow-down/track-down where or what in my code is triggering these exceptions?
In Visual Studio you can break execution when an exception is thrown. Go to debug menu -> exceptions -> Common Language Runtime Exceptions -> System -> System.ObjectDisposedException and check the checkbox for "Thrown".
This exception indicates an attempt to access an object after it has been .Dispose()-ed. The reason the program continues to run is that the exception is handled. a First-Chance exception is always generated when an exception is thrown, even if it is handled with a catch statement.
In general, many first chance exceptions like this are not something to worry about. If you want to track them down, you will need to attach a first chance exception handler, and then use the StackTrace Property to find them. Assuming your Main function is in Program, the following code should work
static Program()
{
AppDomain.CurrentDomain.FirstChanceException += (sender, e) =>
{ // Breakpoint here
};
}
This will give you access to the exception via the e.Exception
Possibly an obvious question to some but couldn't find a duplicate.
I'm packaging the final version of a Windows Forms solution I've been working on and am getting it ready for online distribution. What are the best practices when doing so? We've already had some trouble with packaging the installation file and have run into hurdles to test the program on different PCs, both 32 and 64-bit included.
More specifically, should "throw;" commands be commented out or left in the final release? Would this expose any of the inner workings of the solution itself?
Released application should not crash when exception occurs. You will want to inform the user, something went wrong and log your exception, but you do not want to crash! Informing user should be done in a friendly manner and not just by putting exception.ToString() into the message box.
It is a good practice to add Application.ThreadException or AppDomain.CurrentDomain.UnhandledException handlers to handle all exceptions in your Application. How exactly to do that, is answered in the following thread: Catch Application Exceptions in a Windows Forms Application
However, make sure that your application survives in a usable state, i.e. handle exceptions in a proper way for your application.
I usually add a preprocessor directive for handling exceptions on the application level, since I want them to trow while debugging. For example:
#if !DEBUG
Application.ThreadException += new ThreadExceptionEventHandler(MyHandler);
#endif
It should also be mentioned, that if you have code pieces where you anticipate that Exception might occur, such as network communication error, you should handle those pieces explicitly. What I am saying is, we should not completely forget about exception handling, just because we configured an unhandled exception handler on the application level.
Keep all of your exception handling intact.
Add an event to the starting form in the application, attaching to the Application.UnhandledException event. This will fire if an exception propogates up the stack.
This is the point to inform the user that the application has crashed. Log the error here and then abort gracefully.
Your point about revealing internals, thats up to you to decide. You can obfuscate the source code if you wish, but if you are releasing in Release build mode, and you are not providing the .PDB, then this is the first step.
Ultimately, the DLL / EXE can be decompiled anyway, so its up to you. Debug mode will reveal a lot more than Release mode, but not much more.
Ideally, you should be catching anything that's thrown higher with throw;. Carefully check your code and try to ensure that thrown exceptions are dealt with appropriately. Unhandled exceptions are logged - you can see this information in the Windows Event Viewer. Depending on what details you put in them, unhandled exceptions could give clues as to the inner workings of your application. However, I would suggest that unhandled exceptions are a poor source of information, and that anyone who wanted to know how your application worked could simply disassemble it, unless you've obfuscated it.
Some exceptions cannot be caught by surrounding code with try/catch blocks, so your application should also implement an unhandled exception handler. This gives you the opportunity to show the user an error message and do something with the exception - log it, send it to support, discard it, etc.
I have an application containing both managed and native code. The application currently has an unhandled exception filter, set via SetUnhandledExceptionFilter, which catches any critical errors, generates a minidump, records various application parameters, and exits the program.
The unhandled exception handler does not catch an EngineExecutionException which occurs in the .NET runtime. We suspect the problem is memory corruption caused by the native portion of the application.
The problem is, when the exception occurs, the application just exits without a trace. We'd like to record a minidump when this happens. Does anyone know how our application can install a handler capable of catching this?
AFAIK this exception is not catchable on the managed side of things (at least not in .NET 4).
One way to "catch" it would be to create a (native) custom starter/loader for your application which loads the .NET runtime - this custom starter can install an exception handler on the native side of .NET runtime.
Reference links:
http://msdn.microsoft.com/en-us/magazine/cc163567.aspx
http://msdn.microsoft.com/en-us/library/ms164336.aspx
http://msdn.microsoft.com/en-us/library/dd380851.aspx
http://msdn.microsoft.com/en-us/library/ms231221.aspx
I have a Windows Forms application. It loads assemblies with the extension .Plugin.dll with Assembly.LoadFile. One of these "plugins" calls into another assembly dll. That dll eventually throws a ValidationException exception. The method that throws the exception is in a class that inherits from IDataErrorInfo. This class is a class that is contained in a Linq to SQL class (.dbml). In the "plugin" I call DataContext.SubmitChanges. This is wrapped in a try/catch block. This causes my business logic to validate the data before submitting to the database in the OnValidate override. The result that I see is that after the ValidationExeption is thrown, the debugger stops at the bottom of the OnValidate method indicating that an unhandled exception has occured. If I continue to run the app my catch block is executed. That is what I wanted in the first place, but why am i getting an unhandled exception when it truly is handled?
I am 99% sure your "real" exception causing this is indeed unhandled -this is what the Debugger tells you at first place, and he is generally right.
When you continue to run the App in VS after that, it is not actually what would happen when you will execute your exe out of the debugger. In fact, the debugger notifies you first of the unhandled exception, and then continues some pending logic if any (that's why you see you ValidationException error). But the unhandled exception is still there. I don't exactly know the details and causes of this behavior, but I noticed this many times.
You have to catch the precise error at the precise place where the unhandledexception is thrown after you identify it.
Maybe posting your code sample would help.
Firstly, is the plugin in the same AppDomain?
Secondly, it sounds to be like you have your debugger to "Break when exception is thrown" rather than "Break when exception is user-unhandled".
In VS.NET, go to Debug --> Exceptions...
Expand the "Common Language Runtime Exceptions" node and see if any are ticked.