Chapter 7. Exceptions

 <  Day Day Up  >  

In an ideal world, all programs would execute perfectly and always produce the correct value. In reality, however, bugs and other unexpected situations happen. These situations are dealt with in the .NET Framework through exceptions . An exception is an object that represents an unexpected or exceptional situation. An exception contains information that can be used to help understand what went wrong and where. When an error condition occurs in a program or in the Framework, a new exception object is created and thrown . Throwing an exception causes the program to stop executing and passes control to the .NET Framework, which looks for a specific kind of code, called an exception handler , which can catch the exception and handle it in some specific way.

Style

Exceptions should never just be ignored. Catching an exception and doing nothing but throwing away the exception is a very bad practice that is prone to causing serious bugs. Properly handling exceptions in a program is fundamental to proper execution of a program.


When an exception is thrown, the .NET Framework starts by looking for an exception handler in the method that threw the exception. If the current method has no handler to catch the exception, the Framework looks at the method that called the method that threw the exception. If that method has no handler, it then looks at the method that called the method that called the method that threw the exception, and so on. Eventually, the Framework reaches the Main method. If the Main method does not catch the exception, the exception is considered "unhandled," and the Framework will terminate the program and inform the user that an unhandled exception has occurred.

Style

Because looking for an exception handler incurs a fair amount of overhead (even if the exception handler is in the same method where the exception was thrown), exceptions should only be thrown in truly exceptional situations. Exceptions should not be used in place of returning a value from a function, for example, or communicating some value between two methods through reference parameters.


 <  Day Day Up  >  


The Visual Basic .NET Programming Language
The Visual Basic .NET Programming Language
ISBN: 0321169514
EAN: 2147483647
Year: 2004
Pages: 173
Authors: Paul Vick

Similar book on Amazon

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