Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
A Few Exceptions, A Little IO, and Some Persistent Objects Need try catch on current project and test Rick Mercer 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 a file that is not there (misnamed?) 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 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 transfers to the catch block 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"); } parseDouble public static double parseDouble(String s) 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 may too A small part of Java's large Exception inheritance hierarchy Code that throws RuntimeException need not be in a try block, all others must be in a try block (or avoided) Exception IOException n FileNotFoundExceptio IllegalArgumentException EOFException ArithmeticException RunTimeException NumberFormatException Examples of Exceptions parseDouble and parseInt when the String argument does not represent a valid number Integer expressions that result in division by 0 — Division by 0.0 okay 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 Two Examples of Exceptions String str = null; String strAsUpperCase = str.toUpperCase(); Exception in thread "main" java.lang.NullPointerException List<String> stringList = new ArrayList<String>(); stringList.add("first"); String third = stringList.get(1); IndexOutOfBoundsException: Index: 1, Size: 1 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(); balance = balance + depositAmount; } 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 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 makes you to put this code in a try block (or avoid) line = keyboard.readLine(); } catch (IOException ioe) { System.out.println("Can't read keyboard"); } Now all you have is String readLine(). You parse to int or double Circumventing Exceptions no try catch needed when a method throws Exception // Method declares it might throw any Exception // Because all exceptions can be treated as the // superclass Exception // Circumvent exception handling // |||||||||||||||| public static void main(String[] a) throws Exception { … // No try block line = keyboard.readLine(); theInt = Integer.parseInt(line) … 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 a try block with attempt to read from file catch (FileNotFoundException fnfe) { // Do this if the file was not found in the folder System.out.println("Could not find file: "); } 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"); } 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 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"); } 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] Serializable Any object from a class that lists this in its heading can be written to or read from a disk file implements Serializable ArrayList, String and many Java classes do this The primitive types are also Serializable Classes you write will need the Serializable tag: public class BankAccount // can implement 2 or more implements Comparable, Serializable Serialization errors All instance variables in your classes must also be Serializable! Here, anotherClass is not public class MyClass implements Serializable { AnotherClass a = new AnotherClass(); } private class AnotherClass { // Not serializable } outFile.writeObject(new MyClass()); } catch (IOException ioe) { ioe.printStackTrace(); } Output: java.io.NotSerializableException: AnotherClass at java.io.ObjectOutputStream.writeObject0(Unknown Source)