Errors can occur in a variety of situations. Some of
the most common causes of errors include attempts to divide by zero
(usually caused by invalid input or missing information) and attempts
to connect to a limited resource such as a file or a database (which
can fail if the file doesn't exist, the database connection times out,
or the code has insufficient security credentials).
One infamous type of error is the null reference exception,
which usually occurs when a program attempts to use an uninitialized
object. As a .NET programmer, you'll quickly learn to recognize and
resolve this common but annoying mistake. The following code example
shows the problem in action, with two SqlConnection objects that
represent database connections:
' Define a variable named conOne and create the object.
Private conOne As New SqlConnection()
' Define a variable named conTwo, but don't create it.
Private conTwo As SqlConnection
Protected Sub cmdDoSomething_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles cmdCompute.Click
' This works, because the object has been created
' with the New keyword.
conOne.ConnectionString = "..."
...
' The following statement will fail and generate a
' null reference exception.
' You cannot modify a property (or use a method) of an
' object that doesn't exist!
conTwo.ConnectionString = "..."
...
End Sub
When an error occurs in your code, .NET checks to see whether any error handlers
appear in the current scope. If the error occurs inside a method, .NET
searches for local error handlers and then checks for any active error
handlers in the calling code. If no error handlers are found, the page
processing is aborted, and Visual Studio enters debug mode . If you press the Play button to keep going, you'll see a detailed error page that explains the problem (as shown in Figure 1).
These error pages are a development convenience—once you deploy your
application, they are replaced by more general error pages, which you
can configure in the IIS web server software.
Even if an error is the result of invalid input or
the failure of a third-party component, an error page can shatter the
professional appearance of any application. The application users end
up with a feeling that the application is unstable, insecure, or of
poor quality—and they're at least partially correct.
If an ASP.NET application is carefully
designed and constructed, an error page will almost never appear.
Errors may still occur because of unforeseen circumstances, but they
will be caught in the code and identified. If the error is a critical
one that the application cannot solve on its own, it will report a more
useful (and user-friendly) page of information that might include a
link to a support e-mail or a phone number where the customer can
receive additional assistance.