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.

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

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.

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

Ideally, after the exception is caught the program can fix the problem and continue. Even if your program can't continue, by catching the exception you have an opportunity to print a meaningful error message and terminate gracefully.

It is important to distinguish exceptions from bugs and errors. A bug is a programmer mistake that should be fixed before the code is shipped. An exception is not the result of a programmer mistake (though such mistakes can also raise exceptions). Rather, exceptions are raised as a result of predictable but unpreventable problems that arise while your program is running (e.g., a network connection is dropped or you run out of disk space).

An error is caused by user action. For example, the user might enter a number where a letter is expected. Once again, an error might cause an exception, but you can prevent that by implementing code to validate user input. Whenever possible, user errors should be anticipated and prevented.

Even if you remove all bugs and anticipate all user errors, you will still run into unavoidable problems, such as running out of memory or attempting to open a file that no longer exists. These are exceptions. You cannot prevent exceptions, but you can handle them so that they do not bring down your program.

   


Learning Visual Basic. NET
Learning Visual Basic .Net
ISBN: 0596003862
EAN: 2147483647
Year: 2002
Pages: 153
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net