Effective exception and error handling is one of the most important things to learn in order to write reliable and error-proof applications. In this chapter, we discuss how to use the exception and error handling classes provided by the .NET Framework.
If you come from a C++ background, you're probably familiar with different exception handling methods such as C++ exception handling, structured exception handling, and MFC exceptions. If you come from a Visual Basic (VB) background, you're probably familiar with the On Error statement. Although you can continue to use these techniques to handle errors, .NET implements exceptions differently. In addition, all .NET-supported languages (C# and VB .NET) share the same mechanism. Now VB developers can enjoy the same rich exception handling that C++ developers enjoy.
Discussing .NET exception handling is beyond the scope of this book. In this chapter, we concentrate on ADO.NET exception handling classes only.
VB .NET supports two types of exceptions—unstructured and structured. Remember using the On Error statement in VB? Using the On Error statement is unstructured handling. In other words, you place the On Error statement at the beginning of a block of code and errors are handled at the end of the block. Unstructured exception handling also employs the Error and Resume statements. All the code after the On Error statement is within the scope of the error handler. If there's another On Error statement, then that becomes the active error handler. However, structured exception handling is a better approach, and there's no reason why you should be using the On Error statement.
Structured exception handling works a little differently than unstructured handling. If you come from a C++ background, you're probably familiar with Try...Catch blocks. However, if you haven't encountered them before, it's OK—they're simple enough. Specifically, you place the code within a Try block that you think may cause an exception, and when an exception rises, the control goes to the Catch block.