Post

VB.NET's Try/Catch 'When' Clause

Sometimes I catch myself over thinking things. While showing someone just moving to VB.NET how structured error handling works I mentioned something that C# Try Catch can’t do that VB.NET can. When I stated that I wasn’t sure exactly how you would use the When clause that Catch can handle… he responded with that you could probably use it to increment a attempt counter. BING!!! The light went on. This is how you can use Try Catch in VB.NET to do something similar to the On Error Resume Next functionality!

Apparently, I’m not the only one that was looking at this too close. Several other people have noticed that the When clause is available, but no one could come up with why it would be useful. Here is a small psuedocode sample illustrating how the When clause can be used:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Do
  Dim attempt As Integer
  Try
    ' something that might cause an error.
  Catch ex As IO.FileLoadException When attempt < 3
    ' when we get this exception, ask if the user
    ' wants to to attempt to do it again.
    ' BUT, only attempt this a maximum of 3 times
    If MsgBox("do again?", MsgBoxStyle.YesNo) = MsgBoxResult.No Then
      Exit Do
    End If
  Catch ex As Exception
    ' if any other error type occurs or the attempts are
    ' too many, do the following.
    MsgBox(ex.Message)
    Exit Do
  End Try
  ' increment the attempt counter.
  attempt += 1
Loop

This simple example shows that you could attempt to do some file IO task that could potentially cause an error. An example would be asking the user to put in a floppy disk (I know, how archaic, but hey… it’s an example). If you detect an error, ask them again… but don’t go into infinite loop mode… you only want to ask a couple of times. Once the attempts have failed, then present a different kind of error (or handle the error accordingly).

Without the When clause, this could could get a little bit more complicated. With the When clause, it’s a lot easier to read and understand ;-)

This post is licensed under CC BY 4.0 by the author.