CH 07
CH 07
INPUT/OUTPUT
AND EXCEPTION
HANDLING
Chapter Goals
To read and write text files
To process command line arguments
To throw and catch exceptions
To implement programs that propagate
checked exceptions
while (in.hasNext())
{
char ch = in.next().charAt(0);
// Process each character
}
next returns a one character String
Use charAt(0) to extract the character from the String
at index 0 to a char variable
Classifying Characters
The Character class provides several useful
methods to classify a character:
Pass them a char and they return a boolean
if ( Character.isDigit(ch) ) …
Reading Lines
Some text files are used as simple databases
Each line has a set of related pieces of information
This example is complicated by: China 1330044605
• Some countries use two words India 1147995898
– “United States” United States 303824646
It would be better to read the entire line and process it
using powerful String class methods
while (in.hasNextLine())
{
String line = in.nextLine();
// Process each line
}
int i = 0;
while (!Character.isDigit(line.charAt(i))) { i++; }
Breaking Up Each Line
Use String methods to extract the two parts
United States
String countryName = line.substring(0, i);
String population = line.substring(i); 303824646
// remove the trailing space in countryName
countryName = countryName.trim();
trim removes white space at
the beginning and the end.
Or Use Scanner Methods
Instead of String methods, you can sometimes
use Scanner methods to do the same tasks
Read the line into a String variable United States 303824646
• Pass the String variable to a new Scanner object
Use Scanner hasNextInt to find the numbers
• If not numbers, use next and concatenate words
Scanner lineScanner = new Scanner(line); Remember the
next method
String countryName = lineScanner.next(); consumes white
while (!lineScanner.hasNextInt()) space.
{
countryName = countryName + " " + lineScanner.next();
}
Converting Strings to Numbers
Strings can contain digits, not numbers
They must be converted to numeric types
‘Wrapper’ classes provide a parseInt method
FileNotFoundException
NoSuchElementException
NumberFormatException
Syntax 7.2: Catching Exceptions
Risks:
• The file may not exist
– Scanner constructor will throw an exception
– FileNotFoundException
• The file may have data in the wrong format
– Doesn’t start with a count
» NoSuchElementException
– Too many items (count is too low)
» IOException
Handling Input Errors: main
Outline for method with all exception handling
boolean done = false;
while (!done)
{
try
{
// Prompt user for file name
double[] data = readFile(filename); // May throw exceptions
// Process data
done = true;
}
catch (FileNotFoundException exception)
{ System.out.println("File not found."); }
catch (NoSuchElementException exception)
{ System.out.println("File contents invalid."); }
catch (IOException exception)
{ exception.printStackTrace(); }
}
Handling Input Errors: readFile
Calls the Scanner constructor
No exception handling (no catch clauses)
finally clause closes file in all cases (exception or not)
throws IOException (back to main)
public static double[] readFile(String filename) throws IOException
{
File inFile = new File(filename);
Scanner in = new Scanner(inFile);
try
{
return readData(in); // May throw exceptions
}
finally
{
in.close();
}
}
Handling Input Errors: readData
No exception handling (no try or catch clauses)
throw creates an IOException object and exits
unchecked NoSuchElementException can occur
public static double[] readData(Scanner in) throws IOException
{
int numberOfValues = in.nextInt(); // NoSuchElementException
double[] data = new double[numberOfValues];
for (int i = 0; i < numberOfValues; i++)
{
data[i] = in.nextDouble(); // NoSuchElementException
}
if (in.hasNext())
{
throw new IOException("End of file expected");
}
return data;
}
Summary: Input/Output
Use the Scanner class for reading text files.
When writing text files, use the PrintWriter class
and the print/println/printf methods.
Close all files when you are done processing them.
Programs that start from the command line receive
command line arguments in the main method.
Summary: Processing Text Files
The next method reads a string that is delimited
by white space.
The Character class has methods for classifying
characters.
The nextLine method reads an entire line.
If a string contains the digits of a number, you use
the Integer.parseInt or Double.parseDouble
method to obtain the number value.
Programs that start from the command line
receive the command line arguments in the main
method.
Summary: Exceptions (1)
To signal an exceptional condition, use the throw
statement to throw an exception object.
When you throw an exception, processing
continues in an exception handler.
Place statements that can cause an exception
inside a try block, and the handler inside a catch
clause.
Checked exceptions are due to external
circumstances that the programmer cannot
prevent.
The compiler checks that your program handles these
exceptions.
Summary: Exceptions (2)
Add a throws clause to a method that can throw
a checked exception.
Once a try block is entered, the statements in a
finally clause are guaranteed to be executed,
whether or not an exception is thrown.
Throw an exception as soon as a problem is
detected.
Catch it only when the problem can be handled.
When designing a program, ask yourself what
kinds of exceptions can occur.
For each exception, you need to decide which part
of your program can competently handle it.