typestar

Exceptions in Visual Basic

Try, a filtered Catch, Finally and a custom error of your own.

Try
    Throw New RecipeError("no yeast on hand")
Catch ex As RecipeError When ex.Message.Contains("yeast")
    Console.WriteLine($"specific: {ex.Message}")
Catch ex As Exception
    Console.WriteLine("anything else lands here")
Finally
    Console.WriteLine("kitchen cleaned")
End Try

Class RecipeError
    Inherits Exception

    Public Sub New(message As String)
        MyBase.New(message)
    End Sub
End Class

How it works

  1. Inheriting Exception names a failure precisely.
  2. Catch ... When only catches if the filter expression holds.
  3. The general Catch ex As Exception takes whatever remains.
  4. Finally runs on success and failure alike.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
380
Tokens
78
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 52 seconds.

Type this snippet

Step 2 of 3 in Files & errors, step 26 of 29 in Language basics.

← Previous Next →

Exceptions in other languages