Docsity

Java: Understanding Exception Handling and File I/O, Exams of Computer Science

Toggle sidebar
bg1
1
CS111 Computer Programming
Department of Computer Science
Wellesley College
Exceptions
and
File I/O
Exceptions and File I/O 18-2
Exceptions in Java
oFor reliability: a means of describing and
recovering from run time errors.
oWhen unusual condition arises, program throws
an exception. Code that responds to the
situation catches the exception.
oExceptions are objects whose classes inherit
from the Throwable class.
oUnchecked exceptions (subclasses of Error or
RuntimeException)
oChecked exceptions must be acknowledged.
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Java: Understanding Exception Handling and File I/O and more Exams Computer Science in PDF only on Docsity!

CS111 Computer Programming

Department of Computer Science

Wellesley College

Exceptions

and

File I/O

Exceptions and File I/O 18- 2

Exceptions in Java

o 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 the

situation catches the exception.

o Exceptions are objects whose classes inherit

from the Throwable class.

o Unchecked exceptions (subclasses of Error or

RuntimeException)

o Checked exceptions must be acknowledged.

Exceptions and File I/O 18- 3 List Exceptions class 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 bad Methods in java use exceptions to tell the calling code, “Something bad happened. I failed.” The contract tells us that write() can throw an exception.

Exceptions and File I/O 18- 7 An exception is an object* *Of type Exception. IOException Exception Throwable printStackTrace() 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.

Exceptions and File I/O 18- 9 File I/O: Election 2008 o Electronic voting is very much in the news. o After the citizens vote, the results must be written to a file for safe keeping. o How do we do this? Exceptions and File I/O 18- 10 Writing a String to a text file import 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 FileWriter lives in java.io package The write() method takes a String Tidy up when done

Exceptions and File I/O 18- 13 BufferedWriter import 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 BufferedWriter to FileWriter for more efficient I/O. Exceptions and File I/O 18- 14 The beauty of buffers File I/O without buffers is like shopping without a cart. “George W. Bush” String is chained to FileWriter (connection stream that writes characters as opposed to bytes) “George W Bush John F Kerry” George W Bush John 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

Exceptions and File I/O 18- 15 Reading from a text file import 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 connection stream for characters connecting to text file Chain fileReader to Buffered Reader for more efficient reading Wrap in try/catch Exceptions and File I/O 18- 16 A magic eight ball o We write an “eight ball” program and answers yes/no questions. o The eight ball keeps responses like Without a doubt. It seems unlikely. My sources say no. It is certain. Concentrate and ask again. in a file named answers.txt

Exceptions and File I/O 18- 19 An array might be nice* Without a doubt It seemly unlikely 0 1 MAXANS- private static final MAXANS = 10 ; String [] myArray = new String[MAXANS]; myArray My sources say no … 2 *Why? size

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"; } }

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++; } Without a doubt It seemly unlikely 0 1 MAXANS- myArray My sources say no … 2 size

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++; } Without a doubt It seemly unlikely myArray 0 1 MAXANS- My sources say no … 2 size

Exceptions and File I/O 18- 25 The dice are tossed private 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 class public int intBetween (int lo, int hi) { int result = lo + (Math.abs(rand.nextInt()) % (hi + 1 - lo)); return result; } Without a doubt It seemly unlikely 0 1 MAXANS- myArray My sources say no … 2 size

Exceptions and File I/O 18- 26 Putting it all together public 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"; } }