DEVELOPING EXCEPTION HANDLERS


Runtime errors, also referred to as exceptions, are anomalous conditions that can occur for various reasons. Some examples of exceptions are attempting to process user input that is in an invalid format or attempting to access a system resource, such as a file, that is no longer available. Visual C++ deals with exceptions in one of two ways: either allowing you to handle them or terminating the program (abruptly) with an error message. Obviously, your application's users would probably prefer a graceful error message that might allow them to recover or save their work to a cryptic message that aborts the program.

If you want your applications to handle exceptions, you must anticipate the likely locations where they will occur. Then you must add code that handles the problem. For example, if it is likely that user input would cause an error in a given section of your code, you would include validation checks at that point. Or if your application must access file resources, you should add logic that notifies the user if the required resources are unavailable. There are several other ways to deal with exceptions. For example, you can do the following:

  • Provide a clear, unambiguous, and easy-to-understand error message

  • Give the user a choice and possible courses of action

  • Apologize for the error and close down the application

  • Request that the user report the error

Exception handling gives your application greater flexibility when it encounters runtime errors. By adding exception-handling logic to your Visual C++ applications, you can better contain errors and respond in a more user-friendly fashion. Error handling can also save you the embarrassment of your applications crashing outright.

A Runtime Exception Demonstration

To better understand exception handling, we'll compare how Visual C++ handles exceptions to how your application could possibly handle exceptions. First, load Visual C++ and create a new Windows Forms project. Add to the form a button, and double-click it to cause Visual C++ to generate its click handler. Then add to the button1_C1ick function the following code:

 private: System::Void buttonl_Click(System::Object^  sender, \                                        System::EventArgs^  e) {   String^ strTest = gcnew String("Test");   Int16 intValue = 0;   intValue = Int16::Parse(strTest);   MessageBox::Show( intValue.ToString()  ); } 

Your application has an intentional flaw. Intl6::Parse() is designed to extract numerical contents from a string. However, the string that is supplied to it has a problem. Press F5 to test your application and click the button. Your application should immediately stop running and display results similar to those in Figure 11.9.

image from book
Figure 11.9: Examining the error message that's generated when your application runs into an unhandled exception at runtime.

Visual C++ displays an error dialog box that contains the options of going to the source of the error, continuing execution, or (in some cases) ignoring the error. In the first two cases, your program ceases execution. If you select Break, the application ends, and Visual C++ displays the line that caused the error. At this point, you are still in debug mode, which might allow you to examine other aspects of the program, depending on the severity of the error. If you select Continue, however, your application terminates completely (that is, it crashes).

Now let's see what happens when you use an exception handler. Replace the previous code with the following:

 private: System::Void button1 Click(System::obiect^   sender, \ System::EventArgs^  e) {   String^ strTest = gcnew String("Test");   Int16 intValue = 0;   try   {     intValue = Int16::Parse(strTest);   }   catch(Exception^)   {     MessageBox::Show( "Error: Invalid Data!" );   }   MessageBox::Show( intValue.ToString() ); } 

In this example, the exception handler is made up of try and catch blocks. The try block contains the risky, potentially (or actually, in this case) error-causing code. Should this code fail, the code within the catch block executes. In this example, the results of which are shown in Figure 11.10, the application simply continues executing, ignoring the result of the failure to convert the text within strTest into a number. Although this example is simple, you could use a similar mechanism to validate data from a text box, issuing an error, ignoring the problem, or closing down your application in response.

image from book
Figure 11.10: Exception handling provides a more graceful means of dealing with runtime errors.




Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
ISBN: 735615381
EAN: N/A
Year: 2005
Pages: 131

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