Another interesting use of When

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:

Sub Main()
Try
RunApplication()
Catch ex As Exception
HandleGlobalException(ex)
End Try
End Sub

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:

Sub Main()
Try
RunApplication()
Catch ex As Exception When Not System.Diagnostics.Debugger.IsAttached
HandleGlobalException(ex)
End Try
End Sub

Kind of cute.

2 thoughts on “Another interesting use of When

  1. Pingback: .NET From India

Leave a Reply