Download Data Structures and Java

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CSCI2014 Advanced Software Construction with Java
Exercises: Exceptions
Exercises 4: Exceptions
Reading: C Horstmann, Big Java, Chapter 14. Lecture Notes.
1
Make a table of all the exceptions provided in the java.lang package. Write a comment against each
exception that briefly describes how each one may occur. Also state whether the exception is checked or
unchecked. (see Horstmann section 14.2).
Exception in java.lang
2
Comment
Checked / Unchecked
The following program adds up two numbers, which are provided as command line arguments, arg[0] and
arg[1]. Recall that arg[0] and arg[1] are strings which need to be converted to ints using the
Integer.parseInt() method.
class AddTest {
public static void main(String[] arg) {
int x = Integer.parseInt(arg[0]);
int y = Integer.parseInt(arg[1]);
int sum = x + y;
System.out.println(x + " + " + y + " = " + sum));
}
}
a)
Copy, compile and test the program. Type in both numbers and non-numbers on the command line.
b) Look at the API for Integer.parseInt(String). What Exception does it throw?
c)
Modify your program to catch the exception and take some appropriate action if the command line
arguments are not number strings. Test the program.
d) Get hard copies of your programs, and outputs. File them in your portfolio, and annotate them with
handwritten comments.
3
Create a simple GUI dialogue to accept a number form the user. The frame should contain a prompt "Enter a
number", a text field for the user to type their input, and a message line (i.e. a label) for feedback. Associate an
ActionListener to the text field, which is activated when the user signals the end of input by hitting the 'Enter'
key. Try to convert the string in the text field into a number. If this is successful then output a suitable message
on the message line. Otherwise output an error message, and prompt the user to try again. Use Exceptions to trap
the input error.
4
(Advanced topic) Java version 1.4 has introduced an assert statement, which can be used for debugging and
integrity checks during development. Assertions throw an exception if they fail. Look at his new Java feature at
http://java.sun.com/j2se/1.4/docs/guide/lang/assert.html, and also Horstmann section
8.4. Introduce assertions into your classes.
lz/csci2014/ExceptionExercise.doc/oct03
Page 1