In this lab, you will practice using exceptions and assertions.
you will create two small programs that demonstrate how to use exceptions and assertions.
Preparation
- Review the discussion on exceptions from class.
- Review the recursive code for calculating the Fibonacci numbers from the debugging lab.
- Prepare pseudocode to implement a non-recursive binary search on an array of integers.
Procedure
Set-up
- Get the recursive code for calculating the Fibonacci numbers working in a project.
Lab steps
Part 1 Exceptions
- Revise the Fibonacci code as follows to be able to limit the depth of the recursion:
- Add two parameters to the method: one to say the maximum number of levels of recursion should be allowed and the second to say how deep you are now in the recursion
- When the code calls itself recursively, increment the parameter on how deep you are into the recursion
- Create a custom-made exception called MaximumRecursionDepth that extends the RuntimeException The new exception should include a String message and an int that is the depth of recursion reached. Ensure that your custom-made exception has two methods available:
- getMessage() to return the string message
- getDepth() to return the integer depth that was reached at the time of the exception
- Modify your Fibonacci code to throw a MaximumRecursionDepth exception when the recursion depth exceeds the value of the parameter for the maximum number of levels of recursion.
1
Part 2 Assertions
- Write (non-recursive) code to perform a binary search on a sorted array. You can get help from the Internet for this part; just be sure to cite any sources that you use. This step is not the critical one of the lab.
- Add the following assertions:
- a loop precondition
- a loop invariant
- a postcondition
- Ensure that your assertions are working.
Questions
We usually want you to re-use existing code and infrastructure whenever possible. Why might you create your own exception?
We added parameters to the Fibonacci method. However, those parameters arent very meaningful to a general user. What would you do to the code to make it more accessible for a general user?
How would you recommend for someone to develop a loop invariant?
How can loop invariants help you in programming, even if you dont include them directly as assertions in your code?
Reviews
There are no reviews yet.