Section 12.3. Example: Divide by Zero Without Exception Handling


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.

Figure 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 



[View full width]

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



[View full width]

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 > AllPrograms > 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 informationknown as a stack traceincludes 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:line12) 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 pointthe 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 thrownConvert.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 happensometimes 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.



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net