Lessons in this course (12)

9. Error handling — Try/Catch/Finally and legacy On Error

Intermediate★ Must knowLesson 9 of 12
vb
Try
    Dim text = IO.File.ReadAllText(path)
    Dim n = Integer.Parse(text)
Catch ex As IO.FileNotFoundException
    Log($"Missing file {path}")
Catch ex As FormatException When path.EndsWith(".cfg")   ' exception filter
    Log("Bad config value")
Catch ex As Exception
    Log(ex.ToString())
    Throw                                                ' rethrow, keeps stack trace (never "Throw ex")
Finally
    CleanUp()
End Try

Using conn As New SqlConnection(cs)                      ' = C# using; Dispose at End Using
    conn.Open()
End Using

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

Legacy unstructured error handling (from VB6, still compiles in VB.NET — you'll find it in old code):

vb
Sub OldStyle()
    On Error GoTo ErrHandler          ' jump to label on any error
    Dim x As Integer = CInt("abc")
    Exit Sub
ErrHandler:
    Console.WriteLine("Error " & Err.Number & ": " & Err.Description)
    Resume Next                       ' continue with the next statement (dangerous — hides errors)
End Sub

Refactor On Error to Try/Catch when maintaining such code; On Error Resume Next silently ignores failures.