Chapter 17. Throwing and Catching Exceptions

VB.NET handles errors and abnormal conditions with exceptions. An exception is an object that encapsulates information about an unusual program occurrence, such as running out of memory or losing a network connection. When an exceptional circumstance arises, an exception will be thrown.

Tip

Throwing an exception is sometimes called raising an exception.

You might throw an exception in your own methods (for example, if you realize that an invalid parameter has been provided) or an exception might be thrown in a class provided by the Framework Class Library (for example, if you try to write to a read-only file). Many exceptions are thrown by the runtime when the program can no longer continue due to an operating system problem (such as a security violation).

Tip

VB.NET also provides unstructured exception handling through the use of Error, On Error and Resume statements. This approach is not object oriented and not consistent with how exceptions are handled in other.NET languages. Thus it is discouraged and not shown in this book.

You provide for the possibility of exceptions by adding try/catch blocks in your program. The catch blocks are also called exception handlers. The idea is that you try potentially dangerous code, and if an exception is thrown you catch the exception in your catch block.

Tip

Catching an exception is sometimes referred to as handling the exception.

Ideally, after the exception is caught the program can fix the ...

Get Learning Visual Basic .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.