Java Foundations: Unit 9faculty.washington.edu/jstraub/JavaFoundations/Unit9.pdf ·...

Post on 20-Sep-2020

4 views 0 download

Transcript of Java Foundations: Unit 9faculty.washington.edu/jstraub/JavaFoundations/Unit9.pdf ·...

Java Foundations:Unit 9

Error/Exception Handling

Introduction to Class DiagramsContainment vs. Inheritance

Student

Person

Employee

HireDate

Inheritance:

Student extends PersonEmployee extends Person

Student is‐a Person

is‐arelationship

Containment:

Employee contains HireDate

Employee has‐a HireDate

has‐arelationship

Exception Hierarchy

Error

Object

Exception

IOException

Throwable

RuntimeException

NumberFormatException

Try‐Catch‐Finally• The java.util.Arrays contains the method:

sort(T[] a, Comparator<? super T> c)The T stands for any object type, and the method sorts an array as dictated by the Comparator.

• The documentation for java.util.Comparator<T> (again, the T stands for any object type) says it is an interface, and implementing it requires the two methods:

int compare(T o1, T o2)boolean equals( Object object )

Parsing Numeric StringsThe Integer class provides a variety of utilities for dealing with ints, including:

int parseInt( String str )int parseInt( String str, int radix )

strmust be a valid numeric string. If str is invalid, NumberFormatException is thrown.

Try‐Catch Examplepublic class TryCatchTest{

public static void main(String[] args){

String error = "That wasn't a number!";String prompt = "Please enter a number";String reply =

JOptionPane.showInputDialog( null, prompt );int num = 0;try{

num = Integer.parseInt( reply );}catch ( NumberFormatException exc ){

JOptionPane.showMessageDialog( null, error );}

}}

Checked vs. Unchecked Exceptions (1)

Error Exception

IOException RuntimeException

NumberFormatException

Unchecked Exceptions

Checked Exceptions

. . .

Checked vs. Unchecked Exceptions (2)• Every exception that inherits from Error or RuntimeException are 

unchecked exceptions.• Unchecked exceptions may be ignored by the programmer (at least, 

according to the rules of Java).• Checked exceptions must be caught or declared.• Note: The Exception class itself is a checked exception.

Declaring Checked Exceptions (1)public static void test(){

File infile = new File( "SomeFile.txt" );FileInputStream stream = new FileInputStream( infile );//. . .

}

Compile Error:“unreported exception FileNotFoundException; must be caught or declared to be thrown”

Declaring Checked Exceptions (2)public static void test() throws FileNotFoundException{

File infile = new File( "SomeFile.txt" );FileInputStream stream = new FileInputStream( infile );//. . .

}

Declare a thrown exception with a throws clause.

Throwing ExceptionsYou can raise an exception yourself using the throw keyword.

int num = 0;try{

num = Integer.parseInt( reply );if ( num < 1 || num > 100 )

throw new Exception( "Value out of range" );}catch ( NumberFormatException exc ){

JOptionPane.showMessageDialog( null, error );}catch ( Exception exc ){

JOptionPane.showMessageDialog( null, exc.getMessage() );}

Exercise1. Implement TryCatchTest as shown in your notes; make sure it works.2. In TryCatchTest, add a catch ( Exception exc ) block to the try/catch logic; use 

JOptionPane.showMessageDialog to display exc.getMessage().3. In the try block of TryCatchTest add a check for null returned by the input dialog; if 

it returns null, throw a new Exception with the error message “Invalid operation; no data entered.”

Stream I/O

What is a Stream?A stream is any sequence of bytes of data.

A text stream is a stream of printable characters; records are delimited by line separators.

A binary stream is a stream of data the interpretation of which is entirely under application control; typically, records are a uniform length.

The stdin stream is automatically created and associated with your keyboard; see System.in.

The stdout and stderr streams are automatically created and associated with your display; see System.out and System.err.

Prominent java.io Classes (1)File: Virtual representation of a file (which may or may not exist) in the host system; contains class variables for defining host‐dependent separators.

InputStream: Abstract representation of an input stream; see also System.in.

OutputStream: Abstract representation of an output stream.

PrintStream: An output stream associated with print‐compatible media, such as a display or printer; see also System.out and System.err.

FileReader: Reads text input streams from files.

FileWriter:Writes text output streams to files.

Prominent java.io Classes (2)BufferedReader: Performs buffered reading of a stream.

BufferedWriter: Performs buffered output to a stream.

IOException: Thrown whenever something goes wrong with.

FileNotFoundException: Derives from IOException; thrown when attempting to open an existing file that cannot be found.

Opening a Text File For Outputtry{

FileWriter stream = new FileWriter( "SomeFile.txt" );BufferedWriter writer = new BufferedWriter( stream );

}catch ( IOException exc ){

JOptionPane.showMessageDialog( null, exc.getMessage() );}

Opening a Text File For Outputtry{

FileWriter stream = new FileWriter( "SomeFile.txt" );BufferedWriter writer = new BufferedWriter( stream );. . .

}catch ( IOException exc ){

JOptionPane.showMessageDialog( null, exc.getMessage() );}

Writing To a Text Filetry{

FileWriter stream = new FileWriter( "SomeFile.txt" );BufferedWriter writer = new BufferedWriter( stream );for ( int inx = 0 ; inx < 10 ; ++inx )

writer.write( "Record #" + (inx + 1) + "\n" );writer.close();

}catch ( IOException exc ){

JOptionPane.showMessageDialog( null, exc.getMessage() );}

Don’t forget the line separator!

Opening a Text File For Inputtry{

FileReader stream = new FileReader( "SomeFile.txt" );BufferedReader reader = new BufferedReader( stream );. . .

}catch ( IOException exc ){

JOptionPane.showMessageDialog( null, exc.getMessage() );}

Reading From a Text Filetry{

FileReader stream = new FileReader( "SomeFile.txt" );BufferedReader reader = new BufferedReader( stream );String line = reader.readLine();while ( line != null ){

System.out.println( line );line = reader.readLine();

}}catch ( IOException exc ){

JOptionPane.showMessageDialog( null, exc.getMessage() );}

Automatically strips the line separator.

Reading From stdin

System.out.print( "What? > " );System.out.flush();try{

String line = reader.readLine();while ( line != null && !line.isEmpty() ){

System.out.println( "***" + line + "***" );System.out.print( "What? > " );System.out.flush();line = reader.readLine();

}}catch ( IOException exc ){

JOptionPane.showMessageDialog( null, exc.getMessage() );}

Scanner Is Not Your Friend!public class ScannerTest{

public static void main(String[] args){

String prompt ="Enter a name and two integers> ";

System.out.print( prompt );System.out.flush();Scanner scanner = new Scanner( System.in );

String name = scanner.next();int num1 = scanner.nextInt();int num2 = scanner.nextInt();System.out.println( name + "," + num1 + "," + num2 );

}}

Using Scanner with a file might be worthwhile; I don’t recommend using it in any case where the validity of the input is at all in question.

public class StrtokTest{

public static void main(String[] args)throws Exception

{String prompt =

"Enter a name and two integers> ";System.out.print( prompt );System.out.flush();InputStreamReader inStream =

new InputStreamReader( System.in );BufferedReader reader =

new BufferedReader( inStream );

String line = reader.readLine();parse( line );

}. . .

}

java.util.StringTokenizer (1)

public class StrtokTest{

. . .private static void parse( String line )

throws Exception{

StringTokenizer tizer = new StringTokenizer( line );if ( tizer.countTokens() != 3 )

throw new Exception( "Wrong number of tokens" );String name = tizer.nextToken();int num1 = Integer.parseInt( tizer.nextToken() );int num2 = Integer.parseInt( tizer.nextToken() );System.out.println( name + "," + num1 + "," + num2 );

}}

java.util.StringTokenizer (2)

Also:

StringTokenizer( String str, String delims )StringTokenizer(

String str,String delims,boolean returnDelims

)

Where:delims: Set of delimiters to use when parsing strreturnDelims: If true, delimiters are returned as tokens

java.util.StringTokenizer (3)

Exercise1. Write (and test!) a class method that will ask the operator for a real number; print 

an error message if the operator’s input cannot be converted to type double.2. Write  program that expects a comma‐delimited string of values to be passed from 

the command line; use StringTokenizer to parse the string and print each value.3. Write a program that a) writes 20 lines of data to a file; and b) Opens the file for 

reading, and prints the contents line by line.4. Write a program that asks the operator (via stdin) for a list of integers, then 

computes and prints the average of the numbers. Validate all input; if there is an invalid token print an error message and ask for the list again.

5. a) Write a program that repeatedly prompts the operator for a line of data, then writes the line to a file. End the loop when the operator enters “end.” b) Write a program to open the file and print the contents line by line.