I need to let this sink in… but interesting stuff. try/catch and filters


Somebody posted a comment up my blog which contained something along the lines of  “and VB .NET does the clever try catch stuff that C# can’t” . That got parked at the back of my brain and I finally went off looking for what this was.

Turns out there was a great post on it back in February 2009 on the CLR team blog “Catch, Rethrow and Filters – Why should you care?” .

Turns out VB allows us to inspect an exception without affecting state and conditionally decide whether or not to handle the exception. Notice the use of the When keyword on the Catch:

   1:  Function ShouldCatch(ByVal exception As CustomBaseException) As Boolean
   2:          If TypeOf (exception) Is CustomDontWantToCatchException Then
   3:              Return False
   4:          Else
   5:              Return True
   6:          End If
   7:  End Function
   8:   
   9:  Sub Main()
  10:          Try
  11:              Foo()
  12:          Catch ex As CustomBaseException When ShouldCatch(ex) = True
  13:              Console.WriteLine("Caught exception!")
  14:          End Try
  15:  End Sub

There is also a sample using VB to help C# take advantage of Filters 🙂 http://blogs.msdn.com/junfeng/archive/2008/12/08/exception-filter.aspx 

New to me… was it new to you?

Comments (1)

  1. Steve Hiner says:

    I haven’t ever tried calling another function in the WHEN clause.  I’m going to have to remember that.

    "When" is a handy keyword in certain cases.  Since you can test anything you want to in that clause, you can do stuff like:

    Catch ex as Exception When SomeVariable Is Nothing

    In those cases where there are blocks of IF statements inside a catch you can use WHEN to restructure it a bit and sometimes it makes the code easier to read.