Uutiset

Adafyn kuulumisia

Exception Filters

I have been coding VB.NET for about seven years now and it still keeps surprising me with its features that are missing from C#. Today I stumbled upon exception filters.

Exception filters are way to restrict catch blocks with conditions.

        Try
            MethodThatWillCrash()
        Catch ex As Exception When DateTime.Now.DayOfWeek = DayOfWeek.Monday
            MessageBox.Show(”Exceptions are caught on mondays!”)
        End Try

Exceptions filters are created with When -keyword and condition is specified after it.
This leads us to proper use case.

Catching multiple exceptions in one catch block

    Private Sub SomeMethod()
    Try
            MethodThatWillCrash()
        Catch argException As ArgumentException
        Catch invalidCastException As InvalidCastException
            MessageBox.Show(”Exception!”)
        End Try
    End Sub

    Private Sub MethodThatWillCrash()
        Throw New ArgumentException()
    End Sub

This code will not show messagebox when code is run, because ArgumentException catch block is empty. We could fix it by changing the catch block to check exception type:

       Try
            MethodThatWillCrash()
        Catch generalException As Exception
            If TypeOf generalException Is ArgumentException OrElse TypeOf generalException Is InvalidCastException Then
                MessageBox.Show(”Exception!”)
            Else
                Throw
            End If
        End Try

But the Else statement is dull and catch statement is kind of unclear to read because it catches all exceptions.

        Try
            MethodThatWillCrash()
        Catch generalException As Exception When _
            TypeOf generalException Is ArgumentException OrElse
            TypeOf generalException Is InvalidCastException
            MessageBox.Show(”Exception!”)
        End Try

With When -keyword we can specify types of exception to catch. Neat!

Exception filters posses great strengths, but beware, they can cause some unexpected behaviors: https://blogs.msdn.microsoft.com/dotnet/2009/08/25/the-good-and-the-bad-of-exception-filters/

Btw. exception filters are coming also to C# 6!
http://geekswithblogs.net/BlackRabbitCoder/archive/2015/04/09/c.net-little-wonders-exception-filtering-in-c-6.aspx