Unhandled Exception을 처리하는 방법은 두가지라고 할 수 있다. 하나는 Application.ThreadException에 이벤트 처리기를 연결하는 것이고, 또 다른 것은 AppDomain.UnhandledException에 이벤트 처리기를 연결하는 것이다. UnhandledException에 대해 처음 알게 되었을 때는 만능 열쇠를 찾은 느낌이었다. 특히 MSDN의 예제를 보면 그런 생각이 든다.
하지만 이 예제는 작동하지 않는다. 왜 그런지 이해하려면 John Robbins가 제공하는 예제를 참고하면 된다. UnhandledException 이벤트 처리기는 Main Thread에서는 유효하지 않다.
이를 두고 Code Horror에서는 버그인지 아닌지에 대해 논의가 오갔다. 이때 Jonathan Keljo (Microsft 사람인 듯)이 명쾌한 설명을 해주었다.
Sorry for the confusion. This behavior is actually the design, though the design can be a little convoluted at times.
The first thing to understand is that the UnhandledException event is not an unhandled exception “handler”. Registering for the event, contrary to what the documentation says :-(, does not cause unhandled exceptions to be handled. (Since then they wouldn’t be unhandled, but I’ll stop with the circular reasoning already…) The UnhandledException event simply notifies you that an exception has gone unhandled, in case you want to try to save state before your thread or application dies. FWIW, I have filed a bug to get the docs fixed.
Just to complicate things, in v1.0 and 1.1, an unhandled exception did not always mean that your application would die. If the unhandled exception occurred on anything other than the main thread or a thread that began its life in unmanaged code, the CLR ate the exception and allowed your app to keep going. This was generally evil, because what would often happen was, for example, that ThreadPool threads would silently die off, one by one, until your application wasn’t actually doing any work. Figuring out the cause of this kind of failure was nearly impossible. This may be why Jeff thought it worked before…he just always saw crashes on non-main threads.
In v2.0, an unhandled exception on any thread will take down the application. We’ve found that it’s tremendously easier to debug crashes than it is to debug hangs or the silent-stoppage-of-work problem described above.
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.
CLR Exceptions PM