Understanding Exceptions
An exception occurs when a program encounters any serious problem such as running out of memory or attempting to read from a file that no longer exists. These problems are not necessarily caused by a coding error, but can result from the violation of assumptions that you might have made about the execution environment.
When a program encounters an exception, its default behavior is to throw the exception, which generally translates to abruptly terminating the program after displaying an error message. This is not a characteristic of a robust application and won't make your program popular with users. Your program should be able to handle these exceptional situations and if possible gracefully recover from them. This process is called exception handling. The proper use of exception handling can make your programs robust and easy to develop and maintain. If you don't use exception handling properly, you might end up having a program that performs poorly, is harder to maintain, and can potentially mislead its users.
Whenever possible, an application should fail to a safe state when an exception occurs. You should attempt to prevent your program from doing any damage in case of failure. For example, if you can't be sure that a particular file is no longer needed, don't delete that file if an exception occurs.
Step By Step 3.1 shows the effect of an unhandled exception in an application. Later in this chapter you'll learn how to handle exceptions.
STEP BY STEP 3.1 Exception in a Windows Application
Create a new Visual Basic .NET Windows Application.
Add a new Windows Form to the project.
-
Place three TextBox controls (txtMiles, txtGallons, and txtEfficiency), four Label controls, and a Button control (btnCalculate) on the form's surface. Figure 3.1 shows a design for this form.
Figure 3.1 Mileage Efficiency Calculator.
-
Add the following code to the Click event handler of btnCalculate:
Private Sub btnCalculate_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCalculate.Click ' This code has no error checking. If something ' Goes wrong at run time, it will throw an exception Dim decMiles As Decimal = _ Convert.ToDecimal(txtMiles.Text) Dim decGallons As Decimal = _ Convert.ToDecimal(txtGallons.Text) Dim decEfficiency As Decimal = decMiles / decGallons txtEfficiency.Text = _ String.Format("{0:n}", decEfficiency)
End Sub
-
Set the form as the startup object for the project.
-
Run the project. Enter values for miles and gallons and click the Calculate button to calculate the mileage efficiency as expected. Now enter the value zero in the gallons text box and click the button. You will see the program abruptly terminate after displaying the error message shown in Figure 3.2.
Figure 3.2 DivideByZeroException thrown by the development environment.
When you run an application from the development environment and the program throws an exception, the development environment gives you the opportunity to analyze the problem by debugging the program. If you compile the application and launch it from Windows Explorer, the program will terminate after displaying a message box with error message and some debugging information as shown in Figure 3.3.
Figure 3.3 DivideByZeroException thrown outside the development environment.
The CLR views an exception as an object that encapsulates information about any problems that occurred during program execution. The .NET Framework Class Library provides two categories of exceptions:
ApplicationException: Represents the exceptions thrown by the user programs.
SystemException: Represents the exceptions thrown by the CLR.
Both of these exception classes derive from the base Exception class. The Exception class implements common functionality for exception handling. Neither the ApplicationException class nor the SystemException class adds any new functionality to the Exception class. These classes exist just to differentiate exceptions in user programs from exceptions in the CLR. Table 3.1 lists the important properties of all three classes.
Table 3.1 Important Members of the Exception Class
Property |
Description |
HelpLink |
A URL to the help file associated with this exception. |
InnerException |
Specifies an exception associated with this exception. This property is helpful when a series of exceptions is involved. Each new exception can preserve the information about the previous exception by storing it in the InnerException property. |
Message |
A message that explains the error and possibly offers ways to resolve it. |
Source |
The name of the application that caused the error. |
StackTrace |
Specifies where an error occurred. If debugging information is available, the stack trace includes the source file name and program line number. |
TargetSite |
The method that threw the exception. |