Ok, I think I may have done the “When” thing to death, but Sam Spencer, a PM who used to work on the compiler, pointed out another interesting use of it. Often times, applications will have a global exception handler in the Main method that catches any exceptions that weren’t handled elsewhere. Something like:
Catch ex As Exception
The compiler itself uses a strategy similar to this for out of memory situations — once we’ve run out of memory, the compiler’s toast, so we throw an exception indicating “out of memory” and then catch it at the top level, giving a nice “out of memory, please restart the compiler” error. (Hopefully none of you have ever seen it.)
Anyway, when you’re debugging the application it can be convenient to not catch exceptions at the top level so that you immediately break into the debugger when you get a global exception. A simple way to do this is to use When to not catch the exception when a debugger is present:
Catch ex As Exception When Not System.Diagnostics.Debugger.IsAttached
Kind of cute.
Pingback: .NET From India
Hmm. My feeling is that handling the AppDomain.UnhandledException event is neater, but YMMV.