Lab
2 : Experimenting with Exception Handling
Completed
lab is due by: tomorrow but see DELIVERABLES
below
Getting Ready: Before going any further you should:
Part 1: This part of the lab considers a simple
example of exception handling.
1.
a.
Create
a file named Example1.java
that contains the following code along with your header information:
public class Example1 ratio); } |
b. Compile and execute the application Example1.
c.
What
was output by the application when you executed it?
|
2.
a.
Change
the value of denominator to 0.
b. Re-compile and re-execute Example1.
c.
What
"error" was generated by the application when you executed it?
|
d. Why was this "error" generated
at run-time (rather than at compile-time)?
|
3.
a.
Put
only the statement that generated the exception inside of the try portion of a
try-catch block (and leave the catch block empty. (Hint:
You should be able to determine what exception to catch from the error message
generated during the previous step.)
b. Re-compile Example1.
c.
What
error is generated and why?
|
4.
a.
Move
the "output statement" into the try block (as well).
b. Add the statement System.out.println("Divide
by 0"); to the catch block.
c.
Re-compile
and re-execute Example1.
d. What output was generated?
|
5.
a.
Add
a call to the printStackTrace() method of the ArithmeticException to the catch
block. (Hint:
use javadoc to see how to use this).
b. Re-compile and re-execute Example1.
c.
What
output was generated?
|
d. Did the application execute properly or
not?
|
6.
a.
Change the program to
input the two values to evaluate from the keyboard. Use System.in as your source.
b.
Try running this program
using both examples, 5 and 2 and 5 and 0 as operands
for the division. Did anything change?
|
c.
Create a text file
input.txt. Include one line with the
values 5 and 2 separated by a space. Use
this file as input to the program (change the Scanner source from System.in to
the file (see
either listing 5.11 on page 240 of our text OR one of the ReadFromFile.java
programs in yesterday’s lecture notes).
Read the values from the file. Were there any
differences from keyboard processing to file processing? What did you need to do to compile this program.?
|
Part II: This part of the lab considers an example
of exception handling within and outside of block statements.
public class Example2 try catch (ArithmeticException ae) |
|
|
|
|
|
Part III: This part of the lab considers an
inappropriate use of exception handling and how to "fix" it.
public class Example3 System.out.println("Done"); |
DELIVERABLES