![](http://imgdetail.ebookreading.net/software_development/33/9780470596906/9780470596906__stephens-c-programming__9780470596906__bg128.png)
258
LESSON 21 Handling Errors
EXERCISES
1. Copy the LCM program you built in Lesson 20, Exercise 1 (or download Lesson 20’s version
from the book’s web site) and add error handling to it. If a value causes an error, display a
message and set focus to its textbox. Hints: Validate both the GCD and LCM methods so
they only allow inputs greater than 0. That way they’re both covered if a different program
uses GCD directly. Also use a
try-catch block in the Calculate button’s Click event handler
to protect against format errors.
2. Copy the Fibonacci program you built in Lesson 19, Exercise 2 (or download Lesson 19’s
version from the book’s web site) and add error handling and validation to it. Protect the
program against format errors. Also move the calculation itself into a new method. Make
the method throw an error if its input is less than 0.
3. (SimpleEdit) Copy the SimpleEdit program you built in Lesson 20, Exercise 4 (or download
Lesson 20’s version from the book’s web site) and add error handling to the functions that
open and save files. To test the program, open the file Test.rtf in Microsoft Word. Then make
changes in the SimpleEdit program and try to save them into that file.
4. The quadratic equation finds solutions to equations with the form where a, b, and c are
constants.
The solutions to this equation (the values of x that make it true) are given by the quadratic
formula:
Build a program similar to the one shown in Figure 21-2
that calculates solutions to quadratic equations. Use a
try-catch block to protect against format errors. Hints:
Use
Math.Sqrt to take square roots. The equation has
zero, one, or two real solutions depending on whether the
discriminant b
2
– 4ac is less than, equal to, or greater than
zero. Use
if statements to avoid trying to take the square
root of a negative number.
You can download the solutions to these exercises from the book’s web page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find them in
the Lesson21 folder.
FIGURE 212
596906book.indd 258 4/8/10 7:40:29 AM
Click here to Play