Catching native code exceptions in .NET - c#

I'm currently working with ffmpeg with a proprietary wrapper and I need to catch native code exceptions that sometimes occur during transcoding procedures etc.
I already read those questions/answers:
https://stackoverflow.com/questions/10517199/cant-catch-native-exception-in-managed-code
https://stackoverflow.com/questions/150544/can-you-catch-a-native-exception-in-c-sharp-code
However, they were not really helpful as the exceptions occur not during a function I call, but in a completely different thread that runs side-by-side in the ffmpeg library and were thrown by additional components such as DirectX. This is somehow a real issue as the exceptions tear down my whole application!
Any help is really appreciated.

You can catch exceptions thrown from other threads using these 2 events:
System.Windows.Forms.Application.ThreadException += Application_ThreadException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
// Set the unhandled exception mode to force all Windows Forms errors to go through our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
You might also need to set the following in your App.config file:
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<runtime>
<legacyUnhandledExceptionPolicy enabled="1" />
</runtime>
...
If you can't get it to work with managed code, the code below will catch everything in native (c++) code (not sure if you can PInvoke it):
//Sets the handler for a pure virtual function call.
_set_purecall_handler( &MyPureVirtualCallHandler );
// Sets the handler function to be called when invalid parameters are passed to C runtime functions
_set_invalid_parameter_handler( &MyInvalidParameterHandler );
//Register an unhandled exception filter
SetUnhandledExceptionFilter(&UnhandExceptionFilter);

Related

Catch unhandled exceptions from editor

We are using MEF within our WPF application (MVVM) to embedd external editors. At some point in our main view there is a content element where the editor is going to be placed in.
Now we would like to catch any unhandled exception from that editor and then reload the editor. The only thing I have found is to use DispatcherUnhandledException from the Application class. From there I would have to somehow reach the main view editor and tell it to reload the crashed editor.
I was wondering if there is a "lower" level point, where I could catch the exception? Does anyone have some experience with it and could help he out here?
Thanks
So my answer would be: you better don't if you even could. When you get an unhandled exception, your app is no longer in a stable state. Where exactly would you resume to? What if your external editor throws a Corrupted State Exception (e.g. a Win32 SEH exception) like an AccessViolationException or OutOfMemoryException? Your whole app might be in an undetermined state at that point, so further execution might lead to data loss and/or damage. Furthermore, the CLR might not guarantee that your app can continue:
SEH exceptions are a different class from those exceptions raised by
your program. A program might raise an exception because it tried to
pop an item from an empty stack or tried to open a file that didn't
exist. All of these exceptions make sense in the context of your
program's execution. SEH exceptions refer to a context outside of your
program. Unlike program errors, an SEH exception indicates that the
integrity of the runtime's process may have been compromised.
Please read about SEH and CLR exceptions here.
Here is what I'm not suggesting you to do, but rather for your information: you could prevent your app from closing after catching an unhandled exception by updating your app.config file:
<runtime>
<!-- the following setting prevents the host from closing when an unhandled exception is thrown -->
<legacyUnhandledExceptionPolicy enabled="1" />
</runtime>
But, as Microsoft states, if you ignore exceptions, the application may leak resources and abandon locks.

try/catch not working inside UnhandledException handler

I've got a weird symptom in an application, where try/catches inside the handler for UnhandledExceptions don't work: (that is a breakpoint inside the catch does not get hit, even if the breakpoint inside the try does).
Obviously searching for 'exception unhandled inside UnhandledException' is not working very well for me.
I've tried doing a mini proof-of-concept, and unfortunately that one works.
So while I'm trying to track down the root of the problem, if anyone here has any ideas where to look I'd be greatful.
(We recently changed from XP to Windows7, and .Net 4.5 from 4.0 - I'm pretty certain that previously this worked).
EDIT: Looks like it's provoked by a call down to a (managed) C++ library which is throwing a System.AccessViolationException. Strangely, if I replace the call with a throw new AccessViolationException, it does do what I want...
You wrote, "We recently changed ... .Net 4.5 from 4.0 - I'm pretty certain that previously this worked." but the following seems worth adding, because pretty sure really means not certain :-)
I read somewhere that AccessViolationException cannot occur in managed code, but may be trapped by the runtime for unmanaged code. Maybe the C++ library calls into unmanaged code?
In .NET 4+ the process will terminate after AccessViolationException. Your exception handler will be ignored. This is among a group of exception types considered unrecoverable: Corrupted State Exceptions. In .NET 4+ you will need to customise the app config to override this behaviour.
Be sure that you try to catch System.AccessViolationException and not native Access Violation error.
When you do throw new AccessViolationException it throws System.AccAccessViolationException.
If library that you calls is native it can throw native Access Violation error, but .NET catch block normally can catch only managed exceptions.
try this:
i think we can't handle Unhandeled exception and have to exit application in finally.
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

How to debug / mitigate uncatchable exceptions

So, for a project I have to use the notoriously error prone GDAL (http://www.gdal.org/) library written in unmanaged C++ (actually I'm using the C# bindings). The problem is sometimes the library bombs and crashes the vhost32.exe process. There is nothing I can do about that. Empty catch blocks won't do me no good, the AppDomain.CurrentDomain.UnhandledException isn't even raised.
The exception thrown is
Unhandled exception at 0x77B9AA3C (ntdll.dll) in RASTER.exe: 0xC0000374: A heap has been corrupted (parameters: 0x77BAFE38).
So obviously this exception is unrecoverable and Windows shuts down my process. So far so good. Now the problem is, where to I go from here? I don't want the whole process to be killed just because a call to a buggy library fails. What are my options? Spawning a second process and using named pipes for inter-process communication? That would still mean that the other process crashes with that "Windows is checking for a solution to the problem..." popup. Not good. Unfortunately, for the functionality I need there is no alternative to that library.
<gcConcurrent enabled="false" />
<legacyCorruptedStateExceptionsPolicy enabled="true" />
in my App.config doesn't change a thing. Neither does decorating the method that bombs with the [HandleProcessCorruptedStateExceptions] attribute.
Is there anything I can do?

Can a c# service crash if there is a catch all

I have a service that is started using a start routine surrounded by a try catch block as below.
protected override void OnStart(string[] args)
{
try
{
Program.Start();
}
catch (Exception e)
{
Logger.Error("Exception during Service Start");
}
}
Occasionally on some machines (1/100) it will occasionally print out the last line of Program.Start (a log message) and then fail with no log messages or event log messages. Should this be possible?
Thanks
EDIT: The service does kick off a few other threads but they are encapsulated in the same manner
EDIT: The Logger is a wrapper for log4net - it's working very reliably on a lot (100+) of machines (though yes it possibly the cause)
The service could crash if an exception is thrown out of a started thread but not caught.
Are you adding a handler to each app domain unhandled exception?
eg:
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( CurrentDomain_UnhandledException );
EDIT
Also, you have the Application.ThreadException event which i forgot to mention:
http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx
If the program crashes or an exception is thrown from try block, then for sure youll get Logger.Error log info but not the eventlog from system. If service crash or an unhandled exception occurs, then only eventlog on service is logged.
Yes it could be possible. For instance, a StackOverflowException cannot be catched since .NET 2.0 (see the MSDN article about it).
I am not clear on your question but if you are asking whether your app can crash with a skeleton like that, the chances are very less. Since you have a catch all block almost all kinds of exceptions would be caught and thus your program would end gracefully.
How ever if its a repetive scenario that you are aware of it'd be better to handle it the known way then achieve what you want with an exception as generally execptions for times when something unknown might occur.
Can you put the call to your Logger component in a try-catch block and let us know what happens? Are you able to monitor your service without the Logger component (i.e., based on whatever ouput the service is supposed to be produce - like DB updates)?
Try writing to the event log directly if the call to your Logger component fails. Put this in a try catch block as well. Since the Logger successfully wrote the last line in Program.Start(), it may be something related to unsuccessfully attempting to dispose a resource or something similar, and this is not getting logged.

How to catch ALL exceptions/crashes in a .NET app [duplicate]

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

Categories

Resources