





Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






♦ Chapter Overview
♦ Chapter Objectives
♦ Instructor Notes
♦ Quick Quizzes
♦ Discussion Questions
♦ Projects to Assign
♦ Key Terms
Chapter Overview
This chapter introduces you to one of the tools available in Visual Studio, the Debugger, which can be used to observe the run-time environment and locate logic errors. Using the Debugger, you can stop program execution and inspect the values stored in memory.
This chapter also introduces a special type of error called an exception. Exceptions are usually associated with error conditions that cause abnormal terminations if they are not handled. The try…catch…finally structured exception-handling techniques are demonstrated for dealing with these unexpected conditions.
Chapter Objectives
In this chapter, students will:
Instructor Notes
Visual Studio integrated development environment (IDE) reports errors in your program as soon as it is able to detect a problem. Compiler errors, associated with a language rule violation, are the easiest to discover and eliminate.
Run-Time Errors Sometimes a program stops during execution. Other times, output is produced, but the output might not be correct all the time. Logic errors are normally associated with programs that run but produce incorrect results.
Debugging in C# Visual Studio has a Debugger that enables you to observe the run-time behavior of your program and help locate logic errors. The Debugger lets you break, or halt, the execution of the program to examine the code, evaluate variables in the program, and view the memory space used by your application.
Some circumstances are beyond the control of the programmer. Given perfect situations for running applications, programs may perform beautifully. But, some circumstances are beyond the control of the programmer, and unless provisions are made for handling exceptions, your program may crash or produce erroneous results.
There are a number of things you can do to keep your program from crashing. For example, you can include if statements that check values used as input to ensure the value is numeric, prior to parsing or converting the string value to its numeric equivalent.
You may receive an error message indicating “Unhandled exception” during run time, with the entire application halting. Usually, no errors are detected when the program is compiled. It is only when the application runs that the program crashes and the message is displayed. Sometimes the message will indicate what caused the problem. If the program is running within Visual Studio, the problem code may be highlighted in yellow, with buttons available to stop, break, or stop debugging or continue.
Raising an Exception When a program encounters an error that it cannot recover from, it raises or throws an exception. Execution halts in the current method, and the Common Language Runtime (CLR) attempts to locate an exception handler to handle the exception. An exception handler is a block of code that is executed when an exception occurs.
If an exception handler is found in the current method, control is transferred to that code. If no method is found in the current method, that method is halted and the exception is thrown back to the parent method to handle it. If more than two methods are used, the exception continues to be thrown backwards until it reaches the topmost method. If none of the methods include code to handle the error, the entire application is halted. This can be very abrupt.
Bugs, Errors, and Exceptions In some instances, you can use selection statements, such as if…else, to programmatically prevent your programs from crashing. Bugs differ from exceptions in that they are normally labeled “programmer mistakes” that should be caught and fixed before an application is released. In addition to bugs, programs may experience errors because of user actions. These actions may cause exceptions to be thrown. Entering the wrong type of data from the keyboard is an example of a common user mistake.
A program starts execution in the Main( ) method. From Main( ), it calls on other methods, which can also call on other methods, and so on. When execution reaches the bottom of a given method, control is returned to the method that called it. This continues until control eventually returns to the end of the Main( ) method, where the program finishes its execution. A stack is used to keep up with the execution chain. When an unhandled exception message is displayed in Visual Studio, click the Details button to view a stack trace of methods with the method that raised the exception listed first. A stack trace is a listing of all the methods that are in the execution chain when the exception is thrown. If none of the methods listed in the stack trace include code to handle the type of exception that is encountered, the unhandled exception message is displayed and the program is halted.
Quick Quiz
If an event that creates a problem happens frequently, it is best to write program statements, using conditional expressions, to check for the potential error and provide program instructions for what to do when that problem is encountered. Exceptions are those events from which your program would not be able to recover, such as attempting to read from a data file that does not exist.
Try…Catch…Finally Blocks The code that may create a problem is placed in the try block. The code to deal with the problem (the exception handler) is placed in catch blocks, which are also called catch clauses. The code that you want executed whether an exception is thrown or not is placed in the finally block. More than one catch clause may be included. One is required. If you include an exception type as part of the argument list, only exceptions that match the type listed are handled by that catch clause. The finally clause is also optional.
Control is not returned back into the try block after an exception is thrown. The statement that creates a problem in the try block is the last one tried in the try clause.
Generic Catches If you omit the argument list with the catch clause, it is considered a generic catch. Any exception that is thrown is handled by executing the code within that catch block. The problem with using a generic catch is you are never quite sure what caused the exception to be thrown. You can debug more easily if you know what caused the exception to be thrown.
Exception Object When an exception is thrown, an object is created. The base class for exceptions is Exception; it is part of the System namespace. Exception objects have properties and methods.
Filtering Multiple Exceptions Multiple catch clauses can be included with a single try clause. If more than one is included, the order of placement of these clauses is important. They should be placed from the most specific to the most generic. Because all exception classes derive from the Exception class, if you are including the Exception class, it should always be placed last.
Custom Exceptions You can write your own exception classes. The only requirement is that custom exceptions must derive from the ApplicationException class. Creating an exception class is no different from creating any other class.
Throwing an Exception An exception object is instantiated when “an exceptional condition occurs.” With user-defined exceptions, the CLR does not throw the exception. Instead, the exception is thrown by the program using the throw keyword. When the object is thrown in a method, the exception object propagates back up the call chain, first stopping at the method that called it to see if a catch is available to handle it.
Input Output (IO) Exceptions Exceptions are extremely useful for applications that process or create stored data. The primary exception class for files is System.IO.IOException. System.IO.IOException derives from the SystemException class. An IO.IOException exception is thrown when a specified file or directory is not found, if you attempt to read beyond the end of a file, or if there are problems loading or accessing the contents of a file. Review Table 12-3 for a list of classes derived from the IO.IOException class.
Quick Quiz
This example demonstrates exception-handling techniques. Three classes are constructed for the application. One of the classes is a programmer-defined custom exception class. It inherits methods and properties from the ApplicationException class and is included to illustrate throwing an exception using program statements. The graphical user interface enables the user to enter location name, state where it is located, mile number, and four separate days of water depth at low and high tide. When invalid data is entered, an exception is thrown.
Two additional classes are defined for the application. The business logic for the application is separated from the presentation details. The class that defines the graphical user interface makes use of a try...catch block with multiple catch clauses. This class is used to input the data. After the data is retrieved, it is used to instantiate an object of the third class, the ShoalArea class. Output from the application is displayed in a Windows dialog box.
Do not use exception-handling techniques to deal with problems that can be handled with reasonable coding effort. Always order exceptions from the most specific to the least specific. Encourage students to use meaningful messages with exceptions and to avoid grammatical mistakes.
Discussion Questions
Some interesting topics of discussion in this chapter include:
Projects to Assign
All of the Multiple Choice Exercises, Problems 1- Short answer Problems 21 and 22 Programming Exercises, Problems 2, 6, 8, and 9
Key Terms
¾ breakpoint : selected line in your program that when reached, the program is suspended or placed in break mode ¾ bug : normally labeled “programmer mistakes” that should be caught and fixed before an application is released