Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท Control Flow and Procedures

Error Handling with Try...Catch

Handle errors in Visual Basic .NET with Try...Catch...Finally, exception filters (When), Throw, custom exception classes and Using; learn what not to catch and how to avoid exceptions with validation.

Things go wrong: a file is missing, a user types letters where a number is expected, a network call times out. In .NET such failures are reported as exceptions: objects that interrupt normal flow and travel up the call stack until some code handles them. If nothing handles an exception the program crashes with an error message. VB.NET handles exceptions with Try...Catch...Finally. The older On Error statements exist for VB6 compatibility; do not use them in new code. Listings are VB.NET (read-only); runnable C# stand-ins use the same exception classes.

Try...Catch

Put risky code in a Try block. If an exception is thrown, execution jumps to the first matching Catch:

VB
Try
    Dim text As String = "12x"
    Dim n As Integer = Integer.Parse(text)
    Console.WriteLine(n)
Catch ex As FormatException
    Console.WriteLine("Not a number: " & ex.Message)
End Try

Several Catch blocks can follow one Try. Order them from most specific to most general, because the first matching block wins. All exceptions derive from System.Exception, so Catch ex As Exception catches everything:

VB
Try
    Dim data = File.ReadAllText("settings.json")
    Dim value = Integer.Parse(data)
Catch ex As FileNotFoundException
    Console.WriteLine("Settings file is missing.")
Catch ex As FormatException
    Console.WriteLine("Settings file is corrupt.")
Catch ex As IOException
    Console.WriteLine("Could not read the file: " & ex.Message)
Catch ex As Exception
    Console.WriteLine("Unexpected error: " & ex.GetType().Name)
End Try

Here FileNotFoundException derives from IOException, so it must come first. The compiler warns when an earlier Catch makes a later one unreachable.

Useful exception members

Member Meaning
Message Human-readable description
StackTrace Where it was thrown (call chain)
InnerException The exception that caused this one
GetType().Name The exception class
ToString() Everything above in one string
C# Stand-in (C#): ordered catch blocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Finally and Using

A Finally block runs always: after success, after a handled exception, even when the Try returns. Use it to release resources.

VB
Dim reader As StreamReader = Nothing
Try
    reader = New StreamReader("log.txt")
    Console.WriteLine(reader.ReadLine())
Catch ex As IOException
    Console.WriteLine("I/O problem: " & ex.Message)
Finally
    If reader IsNot Nothing Then reader.Dispose()
End Try

For types that implement IDisposable (files, connections, readers), the Using statement does the same in one step and is the preferred form:

VB
Try
    Using reader As New StreamReader("log.txt")
        Console.WriteLine(reader.ReadLine())
    End Using                    ' Dispose is called here, even if an exception occurs
Catch ex As IOException
    Console.WriteLine("I/O problem: " & ex.Message)
End Try

Filtering with When

A Catch can carry a condition. The block runs only if the expression is true; otherwise the search continues:

VB
Try
    Download(url)
Catch ex As HttpRequestException When ex.Message.Contains("404")
    Console.WriteLine("Page not found")
Catch ex As HttpRequestException
    Console.WriteLine("Network problem")
End Try

Throwing exceptions

Use Throw to report a problem you cannot fix locally. Pick the most specific built-in class: ArgumentNullException, ArgumentOutOfRangeException, InvalidOperationException, NotSupportedException, NotImplementedException.

VB
Function Divide(a As Integer, b As Integer) As Double
    If b = 0 Then
        Throw New ArgumentException("The divisor must not be zero.", NameOf(b))
    End If
    Return a / b
End Function

Inside a Catch, write plain Throw (no argument) to rethrow and keep the original stack trace. Writing Throw ex resets the trace and hides where the failure began.

VB
Catch ex As Exception
    Logger.Write(ex)
    Throw              ' rethrow unchanged

To add context, wrap the original as the inner exception: Throw New InvalidOperationException("Could not save order 17", ex).

Custom exceptions

When callers need to react to a specific business error, create a class that inherits from Exception and provide the standard constructors:

VB
Public Class InsufficientFundsException
    Inherits Exception

    Public ReadOnly Property Missing As Decimal

    Public Sub New(missing As Decimal)
        MyBase.New($"Short by {missing:C}.")
        Me.Missing = missing
    End Sub
End Class
C# Stand-in (C#): throw, custom exception and finally

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Exceptions are for exceptional situations

Throwing and catching is slow compared with normal code and makes flow hard to follow. Check conditions first when you can:

  • Use Integer.TryParse instead of catching FormatException.
  • Check If File.Exists(path) or If dict.ContainsKey(k) or TryGetValue before acting. (Still handle IOException: the file can disappear between the check and the use.)
  • Test If obj IsNot Nothing.

Do not swallow errors with an empty Catch: the program carries on in a broken state and nobody knows why. Do not catch Exception at low levels just to hide problems; catch it at the top of an operation (a button click handler, a request) to log it and show a friendly message. Never catch StackOverflowException or OutOfMemoryException hoping to recover; they usually cannot be handled.

Legacy On Error

You will see On Error Resume Next and On Error GoTo Handler in old code. They are VB6 style, not structured, and easy to misuse. Replace them with Try...Catch when you migrate.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which Catch block order is correct?

    The first matching Catch wins, so specific exception types must come before general ones.
  2. 2. When does a Finally block run?

    Finally runs in every case, which makes it the place for cleanup.
  3. 3. Which statement rethrows the current exception and keeps its stack trace?

    A bare Throw inside Catch preserves the original trace; Throw ex resets it.
  4. 4. What does the Using statement guarantee?

    Using wraps Try/Finally and calls Dispose automatically.
  5. 5. Why prefer Integer.TryParse over catching FormatException?

    Use exceptions for unexpected failures, and validation or TryParse for expected bad input.

Summary

  • Exceptions are objects thrown at failure; Try...Catch...Finally handles them, with specific Catch blocks first.
  • Finally and Using guarantee cleanup; When filters a Catch.
  • Throw reports errors; a bare Throw rethrows while keeping the trace; wrap causes in InnerException.
  • Define custom exceptions for business rules; validate input to avoid exceptions you can predict.
  • Never swallow exceptions silently, and replace legacy On Error code.

Next: Classes and Properties