9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with...

25
9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002 ISBN 1-887902-47-3 Presentation Copyright 2002, Rick Mercer Students who purchase and instructors who adopt Computing Fundamentals with Java by Rick Mercer are welcome to use this presentation as long as this copyright notice remains intact.

Transcript of 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with...

Page 1: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-1

Chapter 9A Few Exceptions, A Little IO, and Some Persistent Objects

Computing Fundamentals with Java Rick Mercer

Franklin, Beedle & Associates, 2002

ISBN 1-887902-47-3

Presentation Copyright 2002, Rick Mercer

Students who purchase and instructors who adopt Computing Fundamentals with Java by Rick Mercer are welcome to use this presentation as long as this copyright notice remains intact.

Page 2: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-2 Exceptions

When programs run, exceptional events occur (a 3rd thing that is sure in life).

Examples of "exceptional events" include:— Division by 0— Attempt to open and it fails— Array subscript out of bounds— Trying to convert a string that is not a number into

a numberHandle these with Java's exception handling.

• General form on next slide

Page 3: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-3 Handling exceptional events

Put code that "throws" exceptional event into a try block and add a catch block.

try { code that cause an exceptional event (throws an exception) } catch(Exception anException) { code that executes when the code in try above throws an exception }

If code in the try block causes an exceptional event, program control transfer to the catch block.

Page 4: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-4 Example

Double.parseDouble may be passed a string that does not represent a valid number.

JTextField depositField = new JTextField("x"); String numberAsString = depositField.getText(); double amount = 0.0;

try { // the next message may "throw an exception" amount = Double.parseDouble(numberAsString); System.out.println("This message may not be sent"); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(null, "'" + numberAsString + "' not valid number"); }

Page 5: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-5 parseDouble

public static double parseDouble(String s) throws NumberFormatExceptionReturns a number new represented by sParameters: s - the string to be parsed.Returns: the double value represented by the string argument.Throws: NumberFormatException - if the string does not

represent a valid number, 1o0.0 for example.

Many methods throw an exception— Your methods could also

Page 6: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-6A small piece of Java's large Exception hierarchy

Code that throws RuntimeException need not be in a try block, all others must be "tried" (there is an alternative).

Exception

IOException IllegalArgumentException RunTimeException

FileNotFoundException EOFException ArithmeticException NumberFormatException

Page 7: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-7 Examples of Exceptions

parseDouble and parseInt when the String argument does not represent a valid number.

Integer expressions that result in division by 0.Sending a message to an object when the

reference variable has the value of null. Indexing exceptions:

— attempting to access an ArrayList element with an index that is out of range or a character in a string outside the range of 0 through length()-1

Page 8: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-8 Two Examples of Exceptions

String str = null;String strAsUpperCase = str.toUpperCase();Output

Exception in thread "main" java.lang.NullPointerException at main(OtherRunTimeExceptions.java:6)

List<String> stringList = new ArrayList<String>();stringList.add("first");String third = stringList.get(1);Output

IndexOutOfBoundsException: Index: 1, Size: 1java.util.ArrayList.RangeCheck(ArrayList.java:491)at java.util.ArrayList.get(ArrayList.java:307)at main(OtherRunTimeExceptions.java:10)

Page 9: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-9 Throwing your own Exceptions

throws and throw are keywords. The object after throw must be an instance of a

class that extends the Throwable class.

public void deposit(double depositAmount) throws IllegalArgumentException { // Another way to handle preconditions if(depositAmount <= 0.0) throw new IllegalArgumentException();

my_balance = my_balance + depositAmount;}

Page 10: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-10 Input/Output Streams

Input is read through input stream objects.Output is written through output stream objects.A stream is a sequence of items read from some

source or written to some destination.Let's show code we needed before the Scanner

type in Java 1.5.

Page 11: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-11Standard input/output

Java has two classes for basic I/O: System.in The "standard" input stream object

(an instance of InputStream) System.out The "standard" output stream

object (an instance of PrintStream) PrintStream has all of the print and println

methods that you have been using. print(Object) print(double) print(int) println(Object) println(double) println(int)

Page 12: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-12 Standard Input the hard way

// Use all of this instead of Scanner keyboard // = new Scanner(System.in); InputStreamReader bytesToChar = new InputStreamReader(System.in); BufferedReader keyboard = new BufferedReader(bytesToChar);

String line = ""; System.out.println("Enter a line of text"); try { // Java forces you to try to read from keyboard line = keyboard.readLine(); } catch (IOException ioe) { System.out.println("Can't read keyboard"); }

Page 13: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-13 Circumventing Exceptions no try catch needed when a method throws Exception

// Method declares it might throw any Exceptionimport java.io.*;public class DeclareExceptionToBeThrown { // Circumvent exception handling // |||||||||||||||| public static void main(String[] a) throws Exception { InputStreamReader bytesToChar = new InputStreamReader(System.in); BufferedReader objectWithReadline = new BufferedReader(bytesToChar); System.out.print("Enter a number: "); String line = objectWithReadline.readLine(); line = line.trim(); // remove blanks double number = Double.parseDouble(line); System.out.println("Number times 2: " + (2 * number)); }}

Page 14: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-14 BufferedReader

The BufferedReader class is often used with InputStreamReader— BufferedReader has a readLine method.

• Example shown on previous slide

BufferedReader is used for: — input from keyboard— Input from a text file

• See next 2 slides

Page 15: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-15 Text input from a File

Since the BufferedReader constructor take a Reader object public BufferedReader(Reader in) — any class that extends Reader can be passed as an

argument to the BufferedReader constructor• InputStreamReader such as Java's System.in object

– For keyboard input• FileReader

– for reading from a file Reader

InputStreamReader

FileReader

Part of Java's inheritance hierarchy. References to InputStreamReader and FileReader can be assigned to a Reader reference (one-way assignment)

Page 16: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-16 Reading from a text file

This program will read lines from a file in the same folder (directory).

double n1 = 0; // Must initialize since try may fail double n2 = 0;

try { // Use a FileReader to read bytes from a disk file FileReader rawBytes = new FileReader("numbers.data"); BufferedReader inputFile = new BufferedReader(rawBytes); n1 = Double.parseDouble(inputFile.readLine()); n2 = Double.parseDouble(inputFile.readLine()); inputFile.close();

Page 17: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-17 Yet Another Detail

A try block may have one to many catch blocks associated with it. There are three things that could go wrong:

} // <- end of try block from previous slide catch (FileNotFoundException fnfe) { // Do this if numbers.dat was not found in the folder System.out.println("Could not find file: " + fnfe); } catch (IOException ioe) { // Do this if a readLine message failed System.out.println("Could not read from file"); } catch (NumberFormatException nfe) { // Do this if a line in the file was not a valid number System.out.println("A numbers on file was bad"); }

Page 18: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-18 FileWriter

A FileWriter object allows you to write to a text file.

PrintWriter diskFile = null; try { FileWriter charToBytesWriter = new FileWriter("out.text"); diskFile = new PrintWriter(charToBytesWriter); } catch (IOException ioe) { System.out.println("Could not create file"); }

// Now diskFile understands print and println diskFile.print("First line with an int: "); diskFile.println(123); diskFile.close(); // Do NOT forget to close

Page 19: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-19 9.3 Persistent Objects

A persistent object is one that stays around after a program terminates.— Can be used by other programs, or when the same

program begins again

Entire objects, even very big ones, can be written to a file on a disk and read from a file on a disk.— The objects must have implements Serializable— Use ObjectOutputStream and its writeObject method— Use ObjectInputStream and its readObject method

Page 20: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-20 Write a list to disk

String fileName = "onelist"; ArrayList<String> list = new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C"); try { FileOutputStream bytesToDisk = new FileOutputStream(fileName); ObjectOutputStream outFile = new ObjectOutputStream(bytesToDisk); // outFile understands the writeObject message. // Make the object persist so it can be read later. outFile.writeObject(list); outFile.close(); // Always close the output file! } catch (IOException ioe) { System.out.println("Writing objects failed"); }

Page 21: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-21 Read the list back in later

try { FileInputStream rawBytes = new FileInputStream(fileName); ObjectInputStream inFile = new ObjectInputStream(rawBytes); // Read the entire object from the file on disk Object anyObject = inFile.readObject(); // Should close input files also inFile.close(); // Now cast Object to the class that it is known to be list = (ArrayList<String>) anyObject; } catch (Exception e) { System.out.println("Something went wrong"); }

System.out.println("The Object persisted: " + list);

Output The Object persisted: [A, B, C]

Page 22: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-22 Serializable

Any object from a class that lists the following in its heading can be written to or read from a disk file.

Implements Serializable

ArrayList, String and many other Java classes do this already.

The primitive types are also persistent.Classes you write may need the Serializable tag: public class BankAccount // can implement 2 or more implements Comparable, Serializable

Page 23: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-23 Bank Teller Done

Optional: Demo BankTeller_Ch9.java— Go to the BankTeller folder on the book's disk— Run the program that writes the BankAccountCollection

and TransactionList objects to disk to set up an initial state (9 account, no transactions). Run this file• InitializeAccountAndTransactionCollections.java

— Run BankTeller_Ch9.java, • Enter the ID Rick (balance 400.00, no transactions)

— Make 3 transactions, quit, save data, and run it again. • Startup again and you'll see the transactions an balance were

remembered via persistent objects

Page 24: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-24 An Object Oriented Program

Bank Teller uses instances of many classes:— 6 Author Supplied classes

• DayCounter, Transaction, TransactionList, BankAccount, BankAccountCollection, BankTeller_Ch9 (extends JFrame)

— 4 ActionListener classes and 1 WindowListener class as inner classes inside the JFrame• WindowClosingListener, ChangeAccountListener,

DepositListener, WithdrawListener, TransactionButtonListener— 10 Standard Java classes

• Object, String, GregorianCalendar, JFrame, JTextField, JButton, JLabel, Calendar, ArrayList, JOptionPane

Page 25: 9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.

9-25 Many Objects

Each object has specific, well-defined services that it must provide (responsibilities).

Most objects send messages to other objects.The Bank Teller is a system of interacting objects.This represents what OO programming is about:

— You don't have one or two classes in isolation— You instantiate many objects from standard Java classes— You write your own classes that are specific to your

problem in order get the needed objects