Introducing Exceptions

In development environments different than .NET, programming languages can handle errors occurring during the application execution in different ways. For example, the Windows native APIs return a 32-bit HRESULT number in case an error occurs. Visual Basic 6 uses the On Error statements, whereas other languages have their own error-handling infrastructure. As you can imagine, such differences cannot be allowed in the .NET Framework because all languages rely on the Common Language Runtime, so all of them must intercept and handle errors the same way. With that said, the .NET Framework identifies errors as exceptions. An exception is an instance of the System.Exception class (or of a class derived from it) and provides deep information on the error occurred. Such an approach provides a unified way for intercepting and handling errors. Exceptions are not only something occurring at runtime, during the application execution.

Exceptions can be thrown by the Visual Basic compiler also at compile time or by the background compiler when typing code. You can also notice that errors occurring when designing the user interface of an application or errors occurring when working within the Visual Studio 2010 IDE are mostly called exceptions. This is because such tasks (and most of the Visual Studio IDE) are powered by the .NET Framework. In Chapter 2, “Getting Started with the Visual Studio 2010 IDE,” we introduced the Visual Studio debugger and saw how it can be used for analyzing error messages provided by exceptions (see the “About Runtime Errors” section in Chapter 2). In that case we did not implement any error handling routine because we just were introducing the debugging features of Visual Studio during the development process. But what if an error occurs at runtime when the application has been deployed to your customer without implementing appropriate error handling code? Imagine an application that attempts to read a file that does not exist and in which the developer did not implement errors checks. Figure 6.1 shows an example of what could happen and that should never happen in a real application.

Figure 6.1 Without handling exceptions, solving errors is difficult.

image

As you can see from Figure 6.1, in case of an error the application stops its execution, and no resume is possible. Moreover, identifying what kind of error occurred can also be difficult. Because of this, as a developer it is your responsibility to implement code for intercepting exceptions and take the best actions possible to solve the problem, also based on users’ choices. The best way to understand exceptions is to begin to write some code that causes an intercept errors, so this is what we are going to do in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.71.159