UG xx.xx: Object Oriented Programing & Web Apps March 2012
Asian Institute of Technology CS/ICT/IT
Handout 01: Lab 03 instructions Instructor: Ramesh Marikhu
Lab 03: Input/Output and Exception Handling
Objectives
Read and write text files
Throw and catch exceptions
Understand the difference between checked and unchecked exceptions
Design your own exception classes
Understand when and where to catch an exception
The Hierarchy of Exception Classes
Figure 1: The Hierarchy of Exception Classes
Self-check questions
1. Q. 1 on page 448 2. Q. 4 on page 455 3. Q. 9 on page 463 4. Q. 12 on page 467 5. Q. 14 on page 469 6. Q. 16 on page 473
In-lab exercises
1. Reading and writing text files
public class ReadWriteFileTest1 {
public static void main(String[] args) {
// Specify a filename directly
File inFile = new File( "text1.txt" );
Scanner in = new Scanner( inFile );
PrintWriter out = new PrintWriter( "text1.out.txt" );
int lineNumber = 1;
// Read the input and write the output while (in.hasNextLine())
{
String line = in.nextLine();
out.println("/* " + lineNumber + " */ " + line);
lineNumber++;
}
in.close();
out.close();
System.out.println( "Program terminated." );
} }
(a) ReadWriteFileTest1: Does the program execute? If not, what is the error displayed?
(b) ReadWriteFileTest2: Solve the error in the above question. What happens when the input file is not found? Is it checked or unchecked exception that is thrown? Why?
(c) ReadWriteFileTest3: Update the program to get input from system console from the user for the input filename and the output filename.
(d) ReadWriteFileTest4: Use try/catch statements to handle exceptions and enable user to re-specify file name. Use try/finally statements to close resources. Also, checked for unchecked exceptions.
Given e is an exception object, what does e.printStackTrace() do?
(e) ReadWriteFileTest5: Update the program to get the input and output filenames using JFile- Chooser. Ensure that all the checked exceptions are handled and make sure that the unchecked exceptions do not occur. Also, enable user to re-specify a valid file name in case ”Cancel” is clicked.
2. Command line arguments
(a) ArgumentChecker1: Write a program that counts the number of arguments provided from the command line or from within Eclipse and print them. Hint: You can provide the arguments in Eclipse IDE from Run >> Run Configuration >> Arguments. You may simply run the program from command line, e.g. java ArgumentChecker1 a bc sdf*e -k=4
public class ArgumentChecker1 {
public static void main(String[] args) {
System.out.println( "No. of arguments = " + ??? );
int iCount = 0;
for( ??? ) {
System.out.println( "arg[" + iCount + "] = " + arg );
iCount++;
} } }
(b) ArgumentChecker2: Parse the arguments and find the inputs specific to option. If the pro- gram is executed using the arguments -d -m 10 -k 0.04, then identify that -d specifies variable bDebugMode is true, value of variable m is 10 and value of variable k=0.04. Ignore other arguments.
Display the values of the variables. Try the following arguments: -k 0.04 -m 10 -d
(c) ArgumentChecker3: Update the program to avoid unchecked exceptions. Hint: Save the argu- ments into a scanner object. Try with the following set of arguments:
-k -m 10 -d
-km 0.04 -m -d -d
-mksdfs -m 334 -D -m 10 -d -k 20
-ksdfs -m 334,6 -D -m 10,5 -d -k 20,.5
Specify the contents of the variabels for each of the above argument lists. Update the program to use comma as delimiter too, along with space. Hint: Use regular expression [Additional resource:
http://www.zytrax.com/tech/web/regex.htm]
3. Designing your own exception classes
Sometimes, the names of the available exception classes may not make perfect sense for the specific exception that you plan to handle. For e.g., if the withdrawal amount is greater than balance, the withdraw operation should not be allowed and instead, InsufficientFundsException must be thrown. This exception class should extend the RuntimeException as it is an unchecked exception. You may also name the exception class as InvalidAmountException.
Need to identify an appropriate name for the exception class.
Need to analyze whether this is a checked or an unchecked exception and should inherit from superclass accordingly.
Review the DataAnalyzer.java and DataSetReader.java for better understanding on how to handle exceptions using try early, catch late approach. An example of a checked exception class (Page 473):
import java.io.IOException
public class BadDataException extends IOException {
public BadDataException(){}
public BadDataException( String message ) {
super(message);
} }
Homework Exercises
1. Exercise R10.16 on page 476 2. Exercise R10.18 on page 477 3. Exercise P10.4 on page 477 4. Exercise P10.6 on page 478 5. Exercise P10.17 on page 479
Submission Guidelines
You should email the homework excercises to [email protected]. Please follow the following submis- sion guidelines:
1. Create a zip file containing a top level folder consisting on your ID and lab number e.g., if your student ID is 106003 and you are submitting lab 7 then the folder name should be 106003-Lab07.
2. Then inside the top level folder you must have a separate folder for every exercise, lets say if you have to submit five exercises then you must have HW1, HW2, HW3, HW4, and HW5 folders inside the top level folder.
3. Every homework exercise folder must contain all Java files (souce code) involved to solve the exercise and a file name execute.sh with the following contents:
javac *.java
java <NAME_OF_CLASS_CONTAINS_MAIN_METHOD>
4. Make sure to email the zip file before starting the next lab session.
For programs, provide the source code and output in your report. Take care to use appropriate fonts for code vs. text.
Submit a hard copy of your report to the lab instructor before the beginning of the next lab session.
Please use both sides of the paper and set font size = 8.