Name: ____________________________________________________ Alpha: _____________________
Describe help received: _________________________________________________________________
Turn in: this sheet, a printout of your code, and a screen
capture showing it running on the five example inputs from
Consider the following program:
Note that this program runs by default in a "quiet" mode,
where only the result gets printed, but with
-v option it runs in a "verbose" mode in
which instructions and an explanation of the output get
printed. Here are some runs of the program:
Several things can go wrong here. Run the program for each of
the following inputs (exactly as shown here!) and summarize
what gets printed/happens, and explain why.
~/$ java HW14 -v
Enter x, k, m: 2 3 5
2^3 % 5 = 3
~/$ java HW14
2 3 5
- 2 4 11
- 2 3 0
- 2 five 17
- 2 -3 5
Use the Java exception handling mechanism to add error
handling to this program. Specifically: In non-verbose mode,
when there is an error absolutely nothing should get printed
out; while in verbose mode, no matter what the error, you
should print out:
Error in HW14! invalid input.
the documentation for Scanner's nextInt()
method to see what it throws and when.
Note on the rules: You may not change what arguments
modexp takes, nor make it non-static,
nor add new static fields to either class.
Note on the point: The point here is to use throw and
try-catch to do all this!
The article "Exception
Handling in C++", Bjarne Strouptrup identifies the four
different "traditional" ways to handle errors listed below.
For each approach, explain specifically why it wouldn't work to provide the
error handling required in Problem 2.
- Terminate the program.
- Return a value representing 'error'
Return a legal value and leave the program in an
This is obviously a disaster, so you don't need to
Call a function supplied to be called in case of
'error'. [e.g. make a call like
handleError("k < 0 in modexp!").]