Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

Visual Basic: Serious error trapping

2011-03-13

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.

Categories: Visual Studio 10

Leave a Reply

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



En kopp kaffe!

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

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips