Deitel & Associates, Inc. Logo

Back to www.deitel.com
digg.png delicious.png blinkit.png furl.png
Visual Basic 2005
How to Program, 3/e

ISBN:
0-13-186900-0
© 2005
pages: ~1500

Order!
Amazon logo

An exception is an indication of a problem that occurs during a program's execution. The name "exception" implies that the problem occurs infrequently—if the "rule" is that a statement normally executes correctly, then the "exception to the rule" is that a problem occurs. Exception handling enables programmers to create applications that can resolve (or handle) exceptions. In many cases, handling an exception allows a program to continue executing as if no problem had been encountered. A more severe problem could prevent a program from continuing normal execution, instead requiring it to notify the user of the problem before terminating in a controlled manner. Exception handling enables programmers to write robust and fault-tolerant programs (i.e., programs that are able to deal with problems that may arise and continue executing). This tutorial demonstrates a program in which a exceptions occur. The program does not process these exceptions, which results in difficult-to-understand error messages being displayed to the user. In Part 2 of this tutorial, we demonstrate how to catch and handle these exceptions. This tutorial is intended for students and professionals who are familiar with classes and basic inheritance concepts in Visual Basic .NET or Visual Basic 2005.

Download the code examples for this tutorial here.

[Note: This three-part tutorial is an excerpt (Sections 12.3-4) of Chapter 12, Exception Handling, from our forthcoming textbook Visual Basic 2005 How to Program, 3/e. This tutorial may refer to other chapters or sections of the book that are not included here. Permission Information: Deitel, Harvey M. and Paul J., Visual Basic 2005 How to Program, ©2005. Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]

12.3 Example: Divide by Zero Without Exception Handling

First we demonstrate what happens when errors arise in a console application that does not use exception handling. Figure 12.1 inputs two integers from the user, then divides the first integer by the second using integer division to obtain an Integer result. In this example, we will see that an exception is thrown (i.e., an exception occurs) when a method detects a problem and is unable to handle it.

Fig. 12.1 | Integer division without exception handling.
   1   ' Fig. 12.1: DivideByZeroNoExceptionHandling.vb
   2   ' An application that attempts to divide by zero.
   3   Module DivideByZeroNoExceptionHandling
   4      Sub Main()
   5         ' get numerator and denominator
   6          Console.Write("Please enter an integer numerator: ")
   7         Dim numerator As Integer = Convert.ToInt32(Console.ReadLine())
   8         Console.Write("Please enter an integer denominator: ")
   9         Dim denominator As Integer = Convert.ToInt32(Console.ReadLine())
   10
   11        ' divide the two integers, then display the result
   12        Dim result As Integer = numerator \ denominator
   13        Console.WriteLine(vbCrLf & _
   14            "Result: {0:D} \ {1:D} = {2:D}", numerator, denominator, result)
   15      End Sub ' Main
   16   End Module ' DivideByZeroNoExceptionHandling

Please enter an integer numerator: 100
Please enter an integer denominator: 7

Result: 100 \ 7 = 14

 

Please enter an integer numerator: 100
Please enter an integer denominator: 0

Unhandled Exception: System.DivideByZeroException:
   Attempted to divide by zero.
   at DivideByZeroNoExceptionHandling.Main()
      in C:\examples\ch12\Fig12_01\DivideByZeroNoExceptionHandling\
      DivideByZeroNoExceptionHandling.vb:line 12

 

Please enter an integer numerator: 100
Please enter an integer denominator: hello

Unhandled Exception: System.FormatException:
   Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options,
      NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style,
      NumberFormatInfo info)
   at System.Convert.ToInt32(String value)
   at DivideByZeroNoExceptionHandling.Main()
      in C:\examples\ch12\Fig12_01\DivideByZeroNoExceptionHandling\
      DivideByZeroNoExceptionHandling.vb:line 9

Running the Application

In most of the examples we have created so far, the application appears to run the same with or without debugging. As we discuss shortly, the example in Fig. 12.1 might cause errors, depending on the user's input. If you run this application using the Debug > Start Debugging menu option, the program pauses at the line where an exception occurs and allows you to analyze the current state of the program and debug it. We discuss the Exception Assistant in Section 12.4.3. We discuss debugging in detail in Appendix C.

In this example, we do not wish to debug the application; we simply want to see what happens when errors arise. For this reason, we execute this application from a Command Prompt window. Select Start > All Programs > Accessories > Command Prompt to open a Command Prompt window, then use the cd command to change to the application's bin\Debug directory. If this application resides in the directory C:\examples\ch12\ Fig12_01\DivideByZeroNoExceptionHandling on your system, you would provide the cd command with the argument

C:\examples\ch12\Fig12_01\DivideByZeroNoExceptionHandling\bin\Debug

in the Command Prompt, then press Enter to change to the application's Debug directory. To execute the application, type

DivideByZeroNoExceptionHandling.exe

in the Command Prompt, then press Enter. If an error arises during execution, a dialog is displayed indicating that the application has encountered a problem and needs to close. The dialog also asks whether you'd like to send information about this error to Microsoft. Since we are creating this error for demonstration purposes, you should click Don't Send. [Note: On some systems a Just-In-Time Debugging dialog is displayed instead. If this occurs, simply click the No button to dismiss the dialog.] At this point, an error message describing the problem is displayed in the Command Prompt. We formatted the error messages in Fig. 12.1 for readability. [Note: Selecting Debug > Start Without Debugging (or <Ctrl> F5) to run the application from Visual Studio executes the application's so-called release version. The error messages produced by this version of the application may differ from those shown in Fig. 12.1 due to optimizations that the compiler performs to create an application's release version.]

Analyzing the Results

The first sample execution in Fig. 12.1 shows a successful division. In the second sample execution, the user enters 0 as the denominator. Note that several lines of information are displayed in response to the invalid input. This information—known as a stack trace—includes the exception name (System.DivideByZeroException) in a descriptive message indicating the problem that occurred and the path of execution that led to the exception, method by method. This information helps you debug a program. The first line of the error message specifies that a DivideByZeroException has occurred. When division by zero in integer arithmetic occurs, the CLR throws a DivideByZeroException (namespace System). The text after the name of the exception, "Attempted to divide by zero," indicates that this exception occurred as a result of an attempt to divide by zero. Division by zero is not allowed in integer arithmetic. [Note: Division by zero with floating-point values is allowed. Such a calculation results in the value infinity, which is represented either by constant Double.PositiveInfinity or constant Double.NegativeInfinity, depending on whether the numerator is positive or negative. These values are displayed as Infinity or -Infinity. If both the numerator and denominator are zero, the result of the calculation is the constant Double.NaN ("not a number"), which is returned when a calculation's result is undefined.]

Each "at" line in the stack trace indicates a line of code in the method that was executing when the exception occurred. The "at" line contains the namespace, class name and method name in which the exception occurred (DivideByZeroNoExceptionHandling.Main), the location and name of the file in which the code resides (C:\examples\ch12\Fig12_01\DivideByZeroNoExceptionHandling\
DivideByZeroNoExceptionHandling.vb:line
12) and the line of code where the exception occurred. In this case, the stack trace indicates that the DivideByZeroException occurred when the program was executing line 12 of method Main. The first "at" line in the stack trace indicates the exception's throw point—the initial point at which the exception occurred (i.e., line 12 in Main). This information makes it easy for you to see where the exception originated, and what method calls were made to get to that point in the program.

Now, let's look at a more detailed stack trace. In the third sample execution, the user enters the string "hello" as the denominator. This causes a FormatException, and another stack trace is displayed. Our earlier examples that input numeric values assumed that the user would input an integer value. However, a user could erroneously input a noninteger value. A FormatException (namespace System) occurs, for example, when Convert method ToInt32 receives a string that does not represent a valid integer. Starting from the last "at" line in the stack trace, we see that the exception was detected in line 9 of method Main. The stack trace also shows the other methods that led to the exception being thrown—Convert.ToInt32, Number.ParseInt32 and Number.StringToNumber. To perform its task, Convert.ToInt32 calls method Number.ParseInt32, which in turn calls Number.StringToNumber. The throw point occurs in Number.StringToNumber, as indicated by the first "at" line in the stack trace.

In Fig. 12.1, the program also terminates when exceptions occur and stack traces are displayed. This does not always happen—sometimes a program may continue executing even though an exception has occurred and a stack trace has been printed. In such cases, the application may produce incorrect results. The next section demonstrates how to handle exceptions to enable the program to run to normal completion.

Other Exception Handling Tutorials:
Example: Divide by Zero Without Exception Handling (You are here).
Example:Handling DivideByZeroExceptions and FormatExceptions

Return to Tutorial Index