A Few Exceptions, A Little IO, and Persistent Objects Rick Mercer.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Lecture 15: I/O and Parsing
Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Yoshi
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
1 Fall 2009ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops.
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
 We can use a combination of the File and FileOutputStream to write a series of bytes to a file.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Lecture 7 File I/O (and a little bit about exceptions)‏
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Java Exception Handling Handling errors using Java’s exception handling mechanism.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
CC1007NI: Further Programming Week 8-9 Dhruba Sen Module Leader (Islington College)
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
Working with files By the end of this lecture you should be able to: explain the principles of input and output and identify a number of different input.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Java I/O Writing and Reading Objects to File Serialization.
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Chapter 11 Exceptions and Input/Output Operations.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
9-1 Chapter 9 A Few Exceptions, A Little IO, and Some Persistent Objects Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 20.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Files and Serialization. Files Used to transfer data to and from secondary storage.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Introduction to Exceptions in Java CS201, SW Development Methods.
CHAPTER 3 File Output.
OO Design and Programming II I/O: Reading and Writing
Java Programming Lecture 2
Accessing Files in Java
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Unit 6 Working with files. Unit 6 Working with files.
Chapter 14 A List ADT.
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Tutorial Exceptions Handling.
Exception Handling Contents
Exceptions.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Exceptions.
Presentation transcript:

A Few Exceptions, A Little IO, and Persistent Objects Rick Mercer

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 a file that does not exist Array subscript out of bounds Integer.parseInt(input) when input is not 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 causes exceptional events } catch( Exception anException ) { code that executes when an exception is thrown }  If code in the try block throws an exception, 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(”ohNo"); JTextField depositField = new JTextField(”ohNo"); 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"); }

parseDouble method heading 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, 1oX.0 for example Many methods throw an exception ○ Your methods may too

A small piece of Java's large Exception hierarchy  Code that throws RuntimeException need not be in a try block, all others must be in a try block Exception IOExceptionIllegalArgumentExceptionRunTimeException FileNotFoundExceptio nEOFExceptionArithmeticExceptionNumberFormatException

A few RuntimeExceptionsRuntimeExceptions  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

Two Unchecked Exceptions String str = null; String strAsUpperCase = str.toUpperCase(); java.lang.NullPointerException List stringList = new ArrayList (); stringList.add("first"); String third = stringList.get(1); IndexOutOfBoundsException: Index: 1, Size: 1

You can throw your own Exceptions which you’ve already done  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(); // This line won’t execute if the exception was thrown // This line won’t execute if the exception was thrown balance = balance + depositAmount; balance = balance + depositAmount;}

Circumventing Exceptions no try catch needed when a method throws Exception  public void aMethod() { // Cause a 2 second pause (in PlayList perhaps) try { try { Thread.sleep(2000); Thread.sleep(2000); } catch (InterruptedException e) { } catch (InterruptedException e) { e.printStackTrace(); e.printStackTrace(); } } } } // This method declares it // might throw any Exception public void aMethod() throws Exception { // To cause a 2 second pause Thread.sleep(2000); } Thread.sleep(2000); } This is how you can circumvent exception handling

Need try /catch to open streams  A stream is a sequence of items read from some source or written to some destination Input is read through input stream objects such as FileInputStream to read bytes Output is written through output stream objects such as FileWriter to print text  We will use other streams to read and write persistent objects Write a large list of objects: writeObject(list)

Reading from a text file // The safe way to find a folder no matter where this program public static void main(String[] args) { 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(); numbers.data

Can have several catch blocks  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.data 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 number on file was not valid"); }

new FileWriters must be in a try block  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

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 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 writeObject Use ObjectInputStream and readObject

Write several object to disk String fileName = "onelist"; ArrayList list = new ArrayList (); list.add("A"); list.add("B"); list.add("C"); try { FileOutputStream bytesToDisk = new FileOutputStream(fileName); ObjectOutputStream outFile = new ObjectOutputStream(bytesToDisk); // outFile understands the writeObject(Object o) message. outFile.writeObject("A String object"); outFile.writeObject(list); outFile.writeObject(123); outFile.writeObject(new GregorianCalendar()); 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); // Need to cast Objects to the class they are known to be String str = (String)inFile.readObject(); list = (ArrayList ) inFile.readObject(); int anInt = (Integer) inFile.readObject(); GregorianCalendar day = GregorianCalendar)inFile.readObject(); System.out.println(" The string: " + str); System.out.println(" The list: " + list.toString()); System.out.println(" anInt: " + anInt); System.out.println("Day Written: " + day); inFile.close(); } catch (Exception e) { System.out.println("Something went wrong"); } Output The string: A String object The list: [A, B, C] anInt: 123 Day Written: java.util.GregorianCalendar [time= ,a

Serializable  Any object from a class that lists this in its heading can be written to or read from a disk file implements Serializable  It’s a tag, there are no methods to implement  Many other Java classes do this already  The primitive types are also Serializable  Classes you write need the Serializable tag: public class BankAccount implements Comparable, Serializable

Serializable Instance Variables  Not only must your class implement Serializable, so must all of the instance variables in the class or mark them as volatile  You will know when you skip this when you see this exception: java.io.NotSerializableException: