View
5
Download
0
Category
Preview:
Citation preview
1
CS111 Computer Programming
Department of Computer ScienceWellesley College
Exceptionsand
File I/O
Exceptions and File I/O 18-2
Exceptions in Javao For reliability: a means of describing and
recovering from run time errors.o When unusual condition arises, program throws
an exception. Code that responds to thesituation catches the exception.
o Exceptions are objects whose classes inheritfrom the Throwable class.
o Unchecked exceptions (subclasses of Error orRuntimeException)
o Checked exceptions must be acknowledged.
2
Exceptions and File I/O 18-3
List Exceptionsclass ListException extends RuntimeException { public ListException (String message) { super(message); }}
class EmptyIntList extends IntList{ ... public int head () { throw new ListException("Cannot take head of empty list"); } public IntList tail () { throw new ListException("Cannot take tail of empty list"); } ...}
Exceptions and File I/O 18-4
When good programs go badMethods in java use exceptions to tell the calling code,“Something bad happened. I failed.”
The contracttells us thatwrite() canthrow an
exception.
3
Exceptions and File I/O 18-5
Risky business
Exceptions and File I/O 18-6
Humoring Javao The compiler needs to
know that YOU knowyou’re calling a riskymethod.
o You can pass the problemalong to your caller
o Or you can wrap the riskycode in something called atry/catch to make thecompiler relax.
4
Exceptions and File I/O 18-7
An exception is an object*
*Of type Exception.
IOException
Exception
ThrowableprintStackTrace()getmessage()
try {
// do risky thing
} catch (Exception ex) {
// try to recover // block runs only // if Exception is // thrown
}
Exceptions and File I/O 18-8
Example: Catching an exception
public static isMember(int n, IntList lst){ try { return (n == head(lst)) || isMember(tail(lst)); } catch (ListException e) { return false; }}
*This is generally considered poor programming practice.
5
Exceptions and File I/O 18-9
File I/O: Election 2008o Electronic voting is very
much in the news.o After the citizens vote,
the results must bewritten to a file for safekeeping.
o How do we do this?
Exceptions and File I/O 18-10
Writing a String to a text fileimport java.io.*;
class WriteAFile{ public static void main (String[] args) { FileWriter writer = new FileWriter (”votes.txt");
writer.write( ”George W. Bush\n” ); writer.write( ”John F. Kerry\n” );
writer.close(); }}
If the file “votes.txt”does not exist,
FileWriter will create it
FileWriterlives in
java.io package
The write() methodtakes a String
Tidy up when done
6
Exceptions and File I/O 18-11
Risky business
Exceptions and File I/O 18-12
Guarding against failureimport java.io.*;
class WriteAFile{ public static void main (String[] args) { try { FileWriter writer = new FileWriter (”votes.txt");
writer.write(”George W. Bush\n”); writer.write(”John F. Kerry\n”);
writer.close();
} catch (IOException ex) { System.out.println(“Voter error. Inform Supreme Court.”); ex.printStackTrace(); } }}
7
Exceptions and File I/O 18-13
BufferedWriterimport java.io.*;
class WriteAFile{ public static void main (String[] args) { try { BufferedWriter writer = new BufferedWriter(new FileWriter (”votes.txt” ));
writer.write(”George W. Bush\n”); writer.write(”John F. Kerry\n”);
writer.close();
} catch (IOException ex) { System.out.println(“Voter error. Inform Supreme Court.”); ex.printStackTrace(); } }}
We chain a BufferedWriterto FileWriter for more
efficient I/O.
Exceptions and File I/O 18-14
The beauty of buffersFile I/O without buffers islike shopping without a cart.
“George W. Bush”
String
is chained to
FileWriter(connection stream
that writes charactersas opposed to bytes)
“George W Bush John F Kerry”
George W BushJohn F.Kerry
File
When the buffer is full,the Strings are all written to
is written to
BufferedWriter(chain stream that
works with characers)
“George W Bush”“John F. Kerry”
String is put into a buffer with other Strings
8
Exceptions and File I/O 18-15
Reading from a text fileimport java.io.*;class ReadAFile{ public static void main (String[] args) { try { File myFile = new File( “votes.txt” );
FileReader fileReader = new FileReader(myFile);
BufferedReader reader = new BufferedReader(fileReader);
String line = null; // holds each input line while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (Exception ex) { ex.printStackTrace(); } }}
FileReader is a connectionstream for charactersconnecting to text file
Chain fileReader to Buffered Reader for
more efficient reading
Wrapin
try/catch
Exceptions and File I/O 18-16
A magic eight ballo We write an “eight ball”
program and answers yes/noquestions.
o The eight ball keepsresponses like Without a doubt. It seems unlikely.
My sources say no.
It is certain.
Concentrate and ask again.
in a file namedanswers.txt
9
Exceptions and File I/O 18-17
Magic8Ballimport java.awt.*;import java.applet.*;public class Magic8Ball { public static void main (String[] args) { System.out.println(StringChooser.chooseLine("answers.txt”)); }}
StringChoose.chooseLine() reads responses from“answers.txt”, then
randomly returns one
Exceptions and File I/O 18-18
First we load our answersimport java.io.*;import java.util.ArrayList;
public class StringChooser{ public static String chooseLine (String inFile) { try { File myFile = new File(inFile); BufferedReader reader = new BufferedReader(new FileReader (myFile));
// But where do we put them all?
reader.close(); } catch (Exception ex) { ex.printStackTrace(); } return ”Ask me again tomorrow"; // Got to return something }}
10
Exceptions and File I/O 18-19
An array might be nice*
Withouta doubt
It seemlyunlikely
0 1 MAXANS-1
private static final MAXANS = 10;String [] myArray = new String[MAXANS];
myArray
…My sourcessay no
2
*Why?
size
6
Exceptions and File I/O 18-20
Stuffing the answers into an array
public class StringChooser{ private static final MAXANS = 10; // Max number of answers allowed public static String chooseLine (String inFile) { String [] myArray = new String[MAXANS]; // Stuff into a String array try { File myFile = new File(inFile); BufferedReader reader = new BufferedReader(new FileReader (myFile));
String line = null; int size = 0; while ((line = reader.readLine()) != null) { myArray[size] = line; size++; }
reader.close(); } catch (Exception ex) { ex.printStackTrace(); } return ”Ask me again tomorrow"; }}
11
Exceptions and File I/O 18-21
Focus please!…private static final MAXANS = 10; // Max number answers allowed… String [] myArray = new String[MAXANS];… String line = null; int size = 0; while ((line = reader.readLine()) != null) { myArray[size] = line; size++; }
Withouta doubt
It seemlyunlikely
0 1 MAXANS-1myArray
…My sourcessay no
2
size
6
Exceptions and File I/O 18-22
Avoiding array out of bounds…private static final MAXANS = 10; // Max number answers allowed… String [] myArray = new String[MAXANS];… String line = null; int size = 0; while (((line = reader.readLine()) != null) && (size < MAXANS)){ myArray[size] = line; size++; }
Withouta doubt
It seemlyunlikely
0 1 MAXANS-1myArray
…My sourcessay no
2
size
6
12
Exceptions and File I/O 18-23
Rolling the dicepublic class StringChooser{ // Stuff from previous slides private static Randomizer rzer = new Randomizer(System.currentTimeMillis()); // Our dice
public static String chooseLine (String inFile) { try { // Stuff in the try block to fill up the array
return (String) (myArray[rzer.intBetween(0,size-1)]);
} catch (Exception ex) { ex.printStackTrace(); } // Rest of program }}
Returns time in milliseconds
for a random seed
Returns a randominteger between
and size-1
Exceptions and File I/O 18-24
Pick a numberimport java.util.*;public class Randomizer { // Instance Variable: private Random rand;
// Constructor Method: public Randomizer (long seed) { rand = new Random(seed); // Set seed for repeatability. } public int intBetween (int lo, int hi) { int result = lo + (Math.abs(rand.nextInt()) % (hi + 1 - lo)); return result; }}
13
Exceptions and File I/O 18-25
The dice are tossedprivate static Randomizer rzer = new Randomizer(System.currentTimeMillis());
private static chooseLine (String filename){ // lots of stuff in between return (String) (myArray[rzer.intBetween(0, size-1)]);}
// meanwhile in the Randomizer classpublic int intBetween (int lo, int hi) { int result = lo + (Math.abs(rand.nextInt()) % (hi + 1 - lo)); return result;}
Withouta doubt
It seemlyunlikely
0 1 MAXANS-1myArray
…My sourcessay no
2
size
6
Exceptions and File I/O 18-26
Putting it all togetherpublic class StringChooser{ private static final MAXANS = 10; // Max number of answers allowed private static Randomizer rzer = new Randomizer(System.currentTimeMillis()); // Our dice public static String chooseLine (String inFile) { String [] myArray = new String[MAXANS]; try { File myFile = new File(inFile); BufferedReader reader = new BufferedReader(new FileReader (myFile)); String line = null; int size = 0; while (((line = reader.readLine()) != null) && (size < MAXANS)) { myArray[size] = line; size++; } reader.close(); return (String) (myArray[rzer.intBetween(0,size-1)]); } catch (Exception ex) { ex.printStackTrace(); } return ”Ask me again tomorrow"; }}
Recommended