• No results found

Lab 03: Input/Output and Exception Handling

N/A
N/A
Protected

Academic year: 2022

Share "Lab 03: Input/Output and Exception Handling"

Copied!
5
0
0

Loading.... (view fulltext now)

Full text

(1)

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

(2)

The Hierarchy of Exception Classes

Figure 1: The Hierarchy of Exception Classes

(3)

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

(4)

(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 ) {

(5)

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.

References

Related documents

Doravirine is a novel once-daily NNRTI for first-line treatment with consistent efficacy regardless of baseline viral load and very good tolerability.. Clin

 A)In case you declare the exception, if exception does not occur, the code will be executed fine.  B)In case you declare the exception if exception occures, an exception will be

1.7.20 A contract under which a provider undertakes, in consideration of an initial payment, to stand ready to provide, or to procure the provision of, legal services on the

A postal survey of British and South Korean shippers was conducted to analyse the operation of the logistics service in the liner shipping industry. The selected sampling method was

Dear Satyanarayana, You can ask upto 3 questions and get reply from our astrologer click here to fill the form and pay... 11/16/2014 Telugu Jathakam | లగ మ ల - Telugu

A selection includes: Sochi 2014, International Paralympic Committee, International Rugby Board, Federation International of Basketball Associations, International Federation

The guidance notes are not intended to replace consultation with specialists from the competent authority, the Agency or other consultees; nor are they intended to cover

Used in metalworking, construction and electrical machinery and equipment, in transportation equipment, as filament in light bulbs, as a carbide in drilling equipment, in heat