Download presentation
Presentation is loading. Please wait.
Published byLeon Banks Modified over 9 years ago
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 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.
2
9-2 Exceptions When programs run, exceptional events occur (a 3 rd 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 number Handle these with Java's exception handling. General form on next slide General form on next slide
3
9-3 Handling exceptional events Put code that "throws" exceptional event into a try block and add a catch block. try { try { code that cause an exceptional event (throws an exception) code that cause an exceptional event (throws an exception) } catch(Exception anException) { catch(Exception anException) { code that executes when the code in try above throws an exception 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.
4
9-4 Example Double.parseDouble may be passed a string that does not represent a valid number. JTextField depositField = new JTextField("x"); JTextField depositField = new JTextField("x"); String numberAsString = depositField.getText(); String numberAsString = depositField.getText(); double amount = 0.0; double amount = 0.0; try { try { // the next message may "throw an exception" // the next message may "throw an exception" amount = Double.parseDouble(numberAsString); amount = Double.parseDouble(numberAsString); System.out.println("This message may not be sent"); System.out.println("This message may not be sent"); } catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(null, JOptionPane.showMessageDialog(null, "'" + numberAsString + "' not valid number"); "'" + numberAsString + "' not valid number"); }
5
9-5 parseDouble public static double parseDouble(String s) throws NumberFormatException throws NumberFormatException Returns a number new represented by s Parameters: 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
6
9-6 A 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 IOExceptionIllegalArgumentExceptionRunTimeException FileNotFoundExceptio nEOFExceptionArithmeticExceptionNumberFormatException
7
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
8
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 stringList = new ArrayList (); stringList.add("first"); String third = stringList.get(1); Output IndexOutOfBoundsException: Index: 1, Size: 1 java.util.ArrayList.RangeCheck(ArrayList.java:491) at java.util.ArrayList.get(ArrayList.java:307) at main(OtherRunTimeExceptions.java:10)
9
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 { throws IllegalArgumentException { // Another way to handle preconditions // Another way to handle preconditions if(depositAmount <= 0.0) if(depositAmount <= 0.0) throw new IllegalArgumentException(); throw new IllegalArgumentException(); my_balance = my_balance + depositAmount; my_balance = my_balance + depositAmount;}
10
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.
11
9-11 Standard input/output Java has two classes for basic I/O: System.in The "standard" input stream object (an instance of InputStream ) System.in The "standard" input stream object (an instance of InputStream ) System.out The "standard" output stream object (an instance of PrintStream ) 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) print(Object) print(double) print(int) println(Object) println(double) println(int) println(Object) println(double) println(int)
12
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"); }
13
9-13 Circumventing Exceptions no try catch needed when a method throws Exception // Method declares it might throw any Exception import 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)); }
14
9-14 BufferedReader The BufferedReader class is often used with InputStreamReader — BufferedReader has a readLine method. Example shown on previous slide Example shown on previous slide BufferedReader is used for: — input from keyboard — Input from a text file See next 2 slides See next 2 slides
15
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 InputStreamReader such as Java's System.in object –For keyboard input FileReader 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)
16
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();
17
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"); }
18
9-18 FileWriter A FileWriter object allows you to write to a text file. PrintWriter diskFile = null; PrintWriter diskFile = null; try { try { FileWriter charToBytesWriter FileWriter charToBytesWriter = new FileWriter("out.text"); = new FileWriter("out.text"); diskFile = new PrintWriter(charToBytesWriter); diskFile = new PrintWriter(charToBytesWriter); } catch(IOException ioe) { catch(IOException ioe) { System.out.println("Could not create file"); System.out.println("Could not create file"); } // Now diskFile understands print and println // Now diskFile understands print and println diskFile.print("First line with an int: "); diskFile.print("First line with an int: "); diskFile.println(123); diskFile.println(123); diskFile.close(); // Do NOT forget to close diskFile.close(); // Do NOT forget to close
19
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
20
9-20 Write a list to disk String fileName = "onelist"; ArrayList list = new ArrayList(); list.add("A"); list.add("B"); list.add("C"); try { FileOutputStream bytesToDisk FileOutputStream bytesToDisk = new FileOutputStream(fileName); = new FileOutputStream(fileName); ObjectOutputStream outFile ObjectOutputStream outFile = new ObjectOutputStream(bytesToDisk); = new ObjectOutputStream(bytesToDisk); // outFile understands the writeObject message. // outFile understands the writeObject message. // Make the object persist so it can be read later. // Make the object persist so it can be read later. outFile.writeObject(list); outFile.writeObject(list); outFile.close(); // Always close the output file! outFile.close(); // Always close the output file!} catch(IOException ioe) { System.out.println("Writing objects failed"); System.out.println("Writing objects failed");}
21
9-21 Read the list back in later try { FileInputStream rawBytes = new FileInputStream(fileName); FileInputStream rawBytes = new FileInputStream(fileName); ObjectInputStream inFile = new ObjectInputStream(rawBytes); ObjectInputStream inFile = new ObjectInputStream(rawBytes); // Read the entire object from the file on disk // Read the entire object from the file on disk Object anyObject = inFile.readObject(); Object anyObject = inFile.readObject(); // Should close input files also // Should close input files also inFile.close(); inFile.close(); // Now cast Object to the class that it is known to be // Now cast Object to the class that it is known to be list = (ArrayList)anyObject; list = (ArrayList)anyObject;} catch(Exception e){ System.out.println("Something went wrong"); System.out.println("Something went wrong");} System.out.println("The Object persisted: " + list); Output The Object persisted: [A, B, C]
22
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 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 public class BankAccount // can implement 2 or more implements Comparable, Serializable implements Comparable, Serializable
23
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 InitializeAccountAndTransactionCollections.java — Run BankTeller_Ch9.java, Enter the ID Rick (balance 400.00, no transactions) 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 Startup again and you'll see the transactions an balance were remembered via persistent objects
24
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) 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 WindowClosingListener, ChangeAccountListener, DepositListener, WithdrawListener, TransactionButtonListener — 10 Standard Java classes Object, String, GregorianCalendar, JFrame, JTextField, JButton, JLabel, Calendar, ArrayList, JOptionPane Object, String, GregorianCalendar, JFrame, JTextField, JButton, JLabel, Calendar, ArrayList, JOptionPane
25
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.