问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/28542783/catch-unhandled-exceptions-from-editor