练习Java中Exception的处理,属于比较基础的Java Lab作业。
Background
Exceptions are a programming tool that allow us to control disruptions in our
program. They essentially allow you to jump out of a series of nested method
calls, back to a previous place in the execution, to handle errors and other
exceptional circumstances. Exceptions are an essential part of the Java
platform, and you need to know about them to use advanced Java techniques.
Before proceeding to the rest of this lab, review the following slides, which
will be presented in the lab: PDF.
Problem 0
An example of authoring and using Exceptions can be found here. Please
download the code, run it, and understand how it works before proceeding to
the problems.
Problem 1
Most of the code we have looked at this semester have natural places where
exceptions could be used.
Download the code for a stack (which includes a unit test) and run it:
IntStack.java. Notice that it contains an error which causes an
ArrayIndexOutOfBounds exception; this can happen in two different places – the
second one is commented out for now.
For this first problem add code using exceptions to address the issue of
underflow caused by the first error.
You should print out the message “Error: Stack underflow!” if it underflows
and do nothing else. You will need to add try-catch blocks to EVERY place
where you use the pop() method.
Problem 2
Now you will create a second exception, which will address the problem of
stack overflow. Instead of resizing, we will throw an exception and report the
number that caused the problem. That is, if you try to push a 4 onto a full
stack, it should say “Error: Stack overflow when pushing 4”. Hint: You need to
put the number which caused the problem into the exception, and then in the
catch block, you need to get the number using getMessage() so you can print it
out. You will need to add try-catch blocks to EVERY place where you use the
push() method.
The usual question asked at this point is: Do I put a try-catch block around
my ENTIRE main, or do I use individual try-catch blocks for each small section
of code? How many try-catch blocks should I use? There is no single answer for
this, but usually you want to do something between the two extremes: it is
better (albeit messier) to use try-catch blocks around the major sections of
your code, where it makes sense to recover from errors and continue with your
program. But there is no one answer to this question.
Submit the file IntStack.java as problem B.1 of HW 11.