Visual Basic: Serious error trapping

The concept of filtering by exception type is familiar to any C# programmer. Visual Basic takes this one step further by also allowing a logical condition that also needs to be true for the block to be executed. If this feature is used, you can have one Try block with multiple Catch section that filters on the same exception class. This is not possible in C# and not allowed in VB without this extra logical condition. The result is better readability and a more logical structure.

Imagine that you want to do an iteration, that fails after three errors. This is the ugly version:

//Do something 10 times, bail after 3 errors.
for (int x = 0; x < 10; x++)
{
   try
   {
      Console.WriteLine("Try something.");
      //This operation will fail.
      throw new Exception();
   }
   catch (Exception ex)
   {
      Console.WriteLine("Failed.");
      if (x >= 2)
      {
         Console.WriteLine("Too many fails. Bail!");
         Console.ReadLine();
         return;
      }
   }
}

And this is the Visual Basic version. Note the When keyword after the Catch keyword:

'Do something 10 times, bail after 3 errors.
For X As Integer = 0 To 9
   Try
      Console.WriteLine("Try something.")
      'This operation will fail.
      Throw New Exception()
   Catch ex As Exception When X < 3
      Console.WriteLine("Failed!")
   Catch ex As Exception
      Console.WriteLine("Too many fails. Bail!")
      Return
   End Try
Next

The way it should be.

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll:

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Comments

Important information: If you have not commented before, your comment will be reviewed before it is published. This means that you will not see it immediately, but I have received it. This is not because I want to filter comments, but because I want to prevent spam and advertising.

Leave a Reply

Your email address will not be published. Required fields are marked *