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:
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.
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.