This goal of this project is to practice handling exceptions. We will do that in the context of some rather odd programming, provided for us by a colleague named Bozo. Bozo is trying out what he thinks are super efficient or compact versions of methods similar to what we've done before. However, nothing seems to be working. Use exception handling to save the day. For each of the three sections (1-3), uncomment the next part of the main method, find out what exceptions are being thrown, and use that to determine what to catch.
Clone the repository for this week's lab:
hg clone /cslab/class/csci235/lab10
Bozo is particularly excited about his method for summing all the elements in an array. Take a look at it. The method takes a shortcut and skips the loop if it's working on an empty array, and all the adding happens in just one line. He particularly likes how the loop header hardly takes up any space. You try to tell him that this will result in an infinite loop, but he insists that when he has tested it, the loop finishes. Sure, the program crashes, but at least the loop does finish.
Fix sum(int[] array)
so that it works correctly,
but do not change or remove any of the lines of code that are already
there (in particular, make sure Bozo's favorite line is untouched).
Instead, just add something around Bozo's favorite line.
Bozo has also written a recursive Fibonacci function. He knows that this recursive version is inefficient, but he doesn't care—it fits all on one line!
Now Bozo is curious... "I wonder what the negative first Fibonacci number is."
When he tries to call fib(-1)
, something goes
wrong, but he can't tell what because the error message fills the entire screen.
To figure out what the problem is (if you can't guess on your own),
try starting a script file and running the program.
Then exit the script and look at the file using your editor or the command less
.
(Typing less filename
will display to the screen the contents of
the file called filename; you can scroll through it using the
arrow keys. Use 'q' to quit.)
Fix this without making any changes to the method fib
.
Instead, wrap the line that calls fib(-1)
with a try and catch.
Bozo has also written an interesting method which he calls rangify
.
It takes an array and an integer n and returns the ratio of the value in the
array at n positions before the midpoint to the value in the array at
n positions after the midpoint.
However, he has tried it on several arrays, and it always causes the program
to crash—in fact, it seems to crash for different reasons every time.
Bozo wants the method fixed so that when it is passed bad parameters it will print a message explaining what is wrong and return the value 0. "But don't use any ifs," Bozo insists.
Script your program's execution. Turn in the typescript and your
source file as lab10
.