Panic in Visual Basic .NET

Our first program will demonstrate the concept of exception handling in Visual Basic .NET. Here’s the full source code:

Imports System
Imports System.IO

Module PanicExample
    Sub Main()
        ' We'll use exception handling throughout this site to check for
        ' unexpected errors. This is the only program on the site designed
        ' to throw an exception.
        Throw New Exception("a problem")

        ' A common use of exception handling is to abort if a function
        ' returns an error that we don't know how to (or want to) handle.
        ' Here's an example of throwing an exception if we get an unexpected
        ' error when creating a new file.
        Try
            Dim fs As FileStream = File.Create("/tmp/file")
        Catch ex As Exception
            Throw New Exception("Error creating file", ex)
        End Try
    End Sub
End Module

Running this program will cause it to throw an exception, print an error message and stack trace, and exit with a non-zero status.

When the first Throw statement in Main executes, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first Throw statement.

$ dotnet run
Unhandled exception. System.Exception: a problem
   at PanicExample.Main() in /path/to/PanicExample.vb:line 8

Note that unlike some languages which use return values for handling of many errors, in Visual Basic .NET it is common to use exception handling for managing unexpected situations.

The Try-Catch block is used to handle exceptions. If an exception occurs within the Try block, the program flow immediately transfers to the Catch block, where you can handle the exception or rethrow it.

In this example, if there’s an error creating the file, we catch the exception and throw a new one with a more specific message, including the original exception as an inner exception. This is similar to the concept of error wrapping in some other languages.

Remember that while exception handling is powerful, it should be used judiciously. For expected error conditions, it’s often better to use return values or other error-handling mechanisms to maintain better control flow and performance in your programs.