Espresso: A Concentrated Introduction to Java

**Summary**: In this laboratory, you will begin working with exceptions in Java.

**Contents**

- Exercises
- Exercise 0: Preparation
- Exercise 1: Exception Basics
- Exercise 2: Computing A Quadratic Root
- Exercise 3: Adding User Input
- Exercise 4: Erroneous Input
- Exercise 5: Indicating Potential Errors
- Exercise 6: Throwing Exceptions
- Exercise 7: Catching Exceptions
- Exercise 8: Specific Exceptions
- Exercise 9: Your Own Exceptions
- Exercise 10: Catching Specific Exceptions

For this laboratory, you will use the `Code`

project and
the previously defined

package.
*username*.util

Don't forget to start Eclipse.

In the

utility class, you should
have a method, *username*.util.IO`readInt`

, that reads an integer. You should
also have written a main class that tests that method.

a. Remove the

from the __throws__ Exception`main`

method and determine what, if any, error messages you get. If Eclipse
permits you to do so, try running the program.

After you finish exploring the effects of that removal, reinsert the throws warning.

b. Remove the

from the definition of
__throws__ Exception`readInt`

and determine what, if any, error messages you
get. If Eclipse permits you to do so, try running the program with
that warning removed.

Do not reinsert the warning.

c. Within `readInt`

, you should have a sequence of lines
(or perhaps a single line) that does something like the following:

String str = br.readLine();returnInteger.parseInt(str);

Enclose those lines in a try/catch clause that returns 0 if an exception is thrown, as in

try{ String str = br.readLine();returnInteger.parseInt(str); }catch(Exception e) {return0; }

Verify that Eclipse is no longer concerned about errors in your code.

Determine what happens when the user enters an invalid value
(such as `Hello`

) in response to a request for an integer.

a. Within

, write a
*username*.util.MyMath`smallQuadraticRoot(`

method that computes the smaller of the two roots of a quadratic.
__double__ a, __double__ b, __double__ c)

Note that you can use the following formula to compute that root:

(-

b- sqrt(b^{2}- 4ac))/2a

You will, of course, have to translate that mathematical expression i into Java code.

b. Write a main class, `TestQR`

, that computes the roots
for a variety of quadratics. Note that it is easiest if you choose
quadratics for which you know the solution. For example,

- If we multiply
*x*-2 and*x*+5, we get*x*^{2}+3-10, we know the roots are 2 and -5. - If we multiply 2
*x*+3) and 3*x*-4), giving us 6*x*^{2}+*x*-12, we know that the roots are -3/2 and 4/3.

c. Extend `TestQR`

to verify that each result is, in fact, a
root of the corresponding function. That is, you should confirm that a*root*root + b*root + c is about 0.

a. Write a new main class, `QR`

, which

- prompts the user for coefficients of a quadratic function,
- computes one root of the quadratic,
- prints that root, and
- prints the value of the quadratic at that root.

b. Use your class to compute a root of *x*^{2}-*x*-2.
Note that the roots of that quadratic are 2 and -1.

a. Determine what happens if the user enters 0 for the coefficient of *x*^{2}.

b. Determine what happens if user enters values for which there is no real root.

c. Determine what happens if the user enters values for which the function
has only one root (e.g., *x*^{2}-2*x*+1 has only one root)?

a. Extend `smallerQuadraticRoot`

to indicate that it may
throw an exception. Note that you'll need
to change the method head for `smallerQuadraticRoot`

to something like
the following

publicstaticdoublesmallerQuadraticRoot(doublea,doubleb,doublec)throwsException

b. Can you successfully compile your modified code? If not, make any changes necessary to permit you to compile it.

c. Can you successfully compile `QR`

? If not, get help from
a tutor or faculty member.

d. What now happens if you enter the erroneous

input described
in the previous exercise?

a. Extend `smallerQuadraticRoot`

so that it throws an exception if
`a`

is 0. For example,

if (a == 0) { throw new Exception("Cannot compute quadratic roots of linear functions."); }

b. Extend `smallerQuadraticRoot`

so that it throws an exception
if the root is not real (i.e., if it has an imaginary component). Note
that the root is not real if the thing you're taking a square root of
is negative.

c. What now happens if you enter the erroneous

input described above?

If you've written your `main`

method using the template
presented earlier, you have the line `throws Exception`

in
the head of that method. Remove that line.

a. What effect do you expect removing that line will have?

b. Verify your answer experimentally. Ask a tutor or teacher if you don't understand the results of your experiment.

c. Enclose your call to `smallerQuadraticRoot`

in a try/catch block.
For example,

try{doubleroot = f.smallerQuadraticRoot(a,b,c); pen.println("The smaller root of the polynomial is:" + root); pen.println("Experimentally," + a + "*" + root + "*" + root" + "+" + b + "*" + root + "+" + c + "=" + (a*root*root + b*root + c)); }catch(Exception e) { pen.println("Sorry, I could not compute a root."); }

d. Determine what happens with the problematic inputs described above.

a. Update `smallerQuadraticRoot`

so that it tries to throw a
`DivideByZeroException`

if the coefficient of the
quadratic term is 0. You can still throw a generic exception
if the result includes an imaginary component.

b. What do you expect to happen when you try to compile the revised program?

c. Verify your answer experimentally.

As you should have determined in the previous exercise, Java does not know by default what
a `DivideByZeroException`

is. Hence, you'll need to create your
own Exception. You do so using the template for user-defined exceptions.

a. Create and compile a Java file for `DivideByZeroException`

.
That is, begin with the template, replace the package name by
your current package name, replace `YourException`

by
`DivideByZeroException`

, and fill in the default message.

b. Verify that the previously-modified code now works.

a. Extend `QR`

so that it has a catch clause for your new
`DivideByZeroException`

*before* the catch clause for
the generic `Exception`

. For example,

try{ ... }catch(DivideByZeroException dbze) { pen.println("Cannot compute a result because the coefficient of the quadratic term is 0."); }catch(Exception e) { ... }

b. Determine what happens in each of the problematic cases.

c. What do your results for this problem suggest?

Tuesday, 22 February 2005 [Samuel A. Rebelsky]

- Created

Wednesday, 21 September 2005 [Samuel A. Rebelsky]

- Minor cleanup for clarity.

Friday, 23 September 2005 [Samuel A. Rebelsky]

- Rewrote many problems to use a new
`Quadratic`

class. - Rewrote the define-your-own exception problem to use a template.

Wednesday, 15 February 2006 [Samuel A. Rebelsky]

- Rewrote the problems to do without that new class, since template class definitions now follow exceptions in the topic order.
- Added some explanations for the less mathematically inclined.
- Improved formatting of formulae.
- Other minor edits.

This page was generated by
Siteweaver on Thu Mar 30 15:24:36 2006.

The source to the page was last modified on Wed Feb 15 11:26:03 2006.

This page may be found at `http://www.cs.grinnell.edu/~rebelsky/Espresso/Labs/exceptions.html`

.

You may wish to validate this page's HTML ; ; Check with Bobby

rebelsky@grinnell.edu