Chapter 12: Exceptions and Advanced File I/O

Slides:



Advertisements
Similar presentations
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Advertisements

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.
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
COMP 121 Week 5: Exceptions and Exception Handling.
© 2012 Pearson Education, Inc. All rights reserved. Chapter 12: Exceptions and Advanced File I/O Starting Out with Java: From Control Structures through.
Starting Out With Java 5 (Early Objects) Chapter 10 By Tony Gaddis Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
12-2 Chapter Topics Chapter 12 discusses the following main topics: Part I: Exceptions Handling Exceptions Throwing Exceptions Part II: More about Input/Output.
COP INTERMEDIATE JAVA Exception Handling Serialization.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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 reference.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
© The McGraw-Hill Companies, 2006 Working with files Chapter 20.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Files and Streams (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
CIS 270—Application Development II Chapter 13—Exception Handling.
Exceptions and Advanced File I/O
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects CS 146 Class Notes Fall 10.
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
Binary Files, Random Access Files Binary Files The way data is stored in memory is sometimes called the raw binary format. Data can be stored in.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter 5: Methods.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 10 Exceptions and Advanced File I/O.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Chapter 11 Exceptions and Input/Output Operations.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 12 Exceptions and Advanced File I/O. 2 Contents I. Handling Exceptions II. Throwing Exceptions III. Advanced Topics 1. Binary Files 2. Random.
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
Appendix H Exception Handling: A Deeper Look
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Chapter 10 – Exception Handling
by Tony Gaddis and Godfrey Muganda
Starting Out with Java: From Control Structures through Objects
Exceptions and Advanced File I/O
Chapter 17 Binary I/O 1.
Chapter 12 Exception Handling and Text IO
Exception Handling Chapter 9.
Chapter 11—Exceptions Handling Exceptions Throwing Exceptions.
Chapter 11: Exceptions and Advanced File I/O
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Starting Out with Java: From Control Structures through Objects
MSIS 670: Object-Oriented Software Engineering
Chapter 12 Exception Handling
Exception Handling Chapter 9 Edited by JJ.
Exception Handling.
Handling Exceptions.
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 12: Exceptions and Advanced File I/O
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
Chapter 6 – Methods Topics are:
Starting Out with Java: From Control Structures through Objects
Exceptions 25-Apr-19.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Exception Handling Contents
Exceptions 10-May-19.
Topics Introduction to File Input and Output
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Exceptions 5-Jul-19.
Exception Handling.
Presentation transcript:

Chapter 12: Exceptions and Advanced File I/O Starting Out with Java: From Control Structures through Data Structures Fourth Edition by Tony Gaddis and Godfrey Muganda With formatting and other updates by Dr. L. Lilien

Chapter Topics Chapter 12 discusses the following main topics: Handling Exceptions Throwing Exceptions More about Input/Output Streams—Advanced File I/O Binary Files, Random Access Files ++OPTIONAL++ Object Serialization Updated by L. Lilien

12.1. Handling Exceptions An exception — an object generated as the result of an error or an unexpected event Exceptions are said to have been “thrown” It is the programmers responsibility to write code that detects and handles exceptions This code implements exception handlers Unhandled exceptions will crash a program Example: BadArray.java Updated by L. Lilien

Handling Exceptions Exception handling — the process of intercepting and responding to exceptions An exception handler — a section of code that gracefully responds to (handles) exceptions The default exception handler deals with unhandled exceptions The default exception handler prints an error message and crashes the program Updated by L. Lilien

Exception Classes RECALL: Any exception is an object NOTE: Classes derived from Error are also exceptions (thrown when critical errors occur) Object Throwable Exception Error RuntimeException IOException FileNotFoundException EOFException … Updated by L. Lilien

Exception Classes An exception is an object Any exception object inherits from a class in the Java hierarchy of exception classes All of the exception classes in the hierarchy are derived from the Throwable class Error and Exception are derived from the Throwable class Updated by L. Lilien

Exception Classes Error subclasses — for exceptions thrown when critical errors occur. E.g.: an internal error in the Java Virtual Machine, or running out of memory Updated by L. Lilien

FileNotFoundException Exception Classes Object Throwable Exception Error RuntimeException IOException FileNotFoundException EOFException … Programmers should not handle the Error subclass exceptions (i.e., exceptions for critical errors) Because they are the result of a serious condition that can’t be fixed by the program Also do not handle the RuntimeException subclass exceptions (cf. p. 754/1) In contrast, programmers should handle other Exception subclass exceptions Updated by L. Lilien

FileNotFoundException Exception Classes Object Throwable Exception Error RuntimeException IOException FileNotFoundException EOFException … The Error subclass exceptions plus the RuntimeException subclass exceptions are unchecked exceptions (cf. p. 754/1) Other Exception subclass exceptions are checked exceptions (cf. p. 754/1) Updated by L. Lilien

Handling Exceptions Try and catch statements are used to handle an exception try { (try block statements...) } catch (ExceptionType ParameterName) (catch block statements...) Updated by L. Lilien

Handling Exceptions A try block is: one or more statements that are executed, and can potentially throw an exception The application will not halt if the try block throws an exception

Handling Exceptions After the try block, a catch clause appears (it is a part of the catch block) catch (ExceptionType ParameterName) ExceptionType is the name of an exception class ParameterName is a variable name of type ExceptionType ParameterName will reference the exception object if the code in the try block throws an exception The parameter must be of a type that is compatible with the thrown exception’s type The code that immediately follows the catch clause is known as a catch block (with the required curly braces) The code in the catch block is executed if the try block throws an exception Updated by L. Lilien

Handling Exceptions Example code — to handle a FileNotFoundException if it is thrown (by the try block) try { File file = new File ("MyFile.txt"); Scanner inputFile = new Scanner(file); } catch (FileNotFoundException e) System.out.println("File not found."); Java Virtual Machine searches for a catch clause that can deal with the exception Example: OpenFile.java Updated by L. Lilien

Handling Exceptions After an exception, the program will continue execution at the point just past the catch block See Fig. 12-4 and 12-5 (p. 739) Updated by L. Lilien

Handling Exceptions Each exception object has a method named getMessage Retrieves the default error message for the exception Example: ExceptionMessage.java ParseIntError.java

Polymorphic References To Exceptions RECALL: A polymorphic reference occurs when a reference variable of a superclass type references subclass objects try { number = Integer.parseInt(str); } catch (Exception e) // instead of: catch (NumberFormatException e) System.out.println("The following error occurred: " + e.getMessage()); The Integer class’s parseInt method throws a NumberFormatException object The NumberFormatException class is a subclass of Exception Updated by L. Lilien

Polymorphic References To Exceptions As shown on the previous slide, when handling exceptions, you can use a polymorphic reference as a parameter in the catch clause A catch clause that uses a parameter variable of the Exception type can catch any exception that is a subclass of Exception Most exceptions are derived from the Exception class Updated by L. Lilien

Exception Handlers A try block can have many polymorphic catch clauses With only one catch clause for each specific exception type try { number = Integer.parseInt(str); } catch (NumberFormatException e) System.out.println("Bad number format."); catch (NumberFormatException e) // ERROR!!! System.out.println(str + " is not a number."); Updated by L. Lilien

Handling Multiple Exceptions The try block can throw > 1 type of exception Needs a catch clause for each type of exception that could potentially be thrown JVM executes the first compatible catch clause found These catch clauses must be listed in the order from the most specific to the most general Updated by L. Lilien

Exception Handlers NumberFormatException is a subclass of IllegalArgumentException (NFE is more specific than IAE) try { number = Integer.parseInt(str); } catch (IllegalArgumentException e) System.out.println("Bad number format."); catch (NumberFormatException e) // ERROR!!! Bec. more // specific follows more general System.out.println(str + " is not a number."); Updated by L. Lilien

Exception Handlers The previous code could be corrected as follows: try { number = Integer.parseInt(str); } catch (NumberFormatException e) System.out.println(str + " is not a number."); catch (IllegalArgumentException e) //OK Bec. more // general follows more specific System.out.println("Bad number format."); Example: SalesReport.java, SalesReport2.java Updated by L. Lilien

The finally Clause The try statement may have an optional finally clause. If present, the finally clause must appear after all of the catch clauses. try { (try block statements...) } catch (ExceptionType ParameterName) (catch block statements...) finally (finally block statements...) Updated by L. Lilien

The finally Clause The finally block always executed after the try block has executed after any catch blocks have executed if an exception was thrown The statements in the finally block execute whether an exception occurs or not Updated by L. Lilien

The Stack Trace The call stack is an internal list of all the methods that are currently executing A stack trace = a list of all the methods in the call stack It shows: the method that was executing when an exception occurred and all of the methods that were called in order to execute that method Example: StackTrace.java Updated by L. Lilien

Uncaught Exceptions When an exception is thrown, it cannot be ignored It must be handled by the program, or by the default exception handler When a method throws an exception: normal execution of that method stops JVM searches for a compatible exception handler inside the method (cont.) Updated by L. Lilien

Uncaught Exceptions If no exception handler inside the method: control of the program is passed to the previous method in the call stack If that method has no exception handler, then control is passed again, up the call stack, to the previous method If control reaches the main method: If the main method can, it handles the exception Otherwise, the program is halted and the default exception handler executes Updated by L. Lilien

Checked and Unchecked Exceptions Two exception categories: Unchecked exceptions Derived from the Error class or the RuntimeException class Derived from Error, thrown when a critical error occurs Derived from RuntimeException, thrown by programming errors Can be avoided with properly written code Unchecked exceptions, in most cases, should not be handled Checked exceptions Exceptions not derived from Error or RuntimeException Updated by L. Lilien

Checked and Unchecked Exceptions A method that can throw a checked exception: must handle the exception or must have a throws clause listed in the method header throws informs the compiler what exceptions can be thrown by a method Updated by L. Lilien

Checked and Unchecked Exceptions // This method will not compile! (bec. can // throw a checked exception but does not list // it with a throws clause in its header) public void displayFile(String name) { // Open the file. File file = new File(name); Scanner inputFile = new Scanner(file); // Read and display the file's contents. while (inputFile.hasNext()) System.out.println(inputFile.nextLine()); } // Close the file. inputFile.close(); Updated by L. Lilien

Checked and Unchecked Exceptions The code in this method is capable of throwing checked exceptions The preceding code will compile when the method header is corrected as follows: public void displayFile(String name) throws FileNotFoundException

12.2. Throwing Exceptions You can write code that: throws a standard Java exception or throws an a custom exception (designed by you) The throw statement is used to explicitly throw an exception throw new ExceptionType(MessageString); The throw statement causes an exception object to be created and thrown Updated by L. Lilien

Throwing Exceptions throw new ExceptionType(MessageString); MessageString contains a custom error message It can be retrieved by the exception object’s getMessage method If you do not pass a message, the exception will have a null message Example of passing a message: throw new Exception("Out of fuel"); Note: Don’t confuse the throw statement with the throws clause Example: DateComponentExceptionDemo.java Updated by L. Lilien

Creating Exception Classes You can create your own exception classes by deriving them from the Exception class (deriving directly or indirectly) Some examples of exceptions that can affect a bank account: A negative starting balance is passed to the constructor A negative interest rate is passed to the constructor A negative number is passed to the deposit method A negative number is passed to the withdraw method The amount passed to the withdraw method exceeds the account’s balance We can create exceptions for each of these error conditions Updated by L. Lilien

Creating Exception Classes Some examples of exceptions that can affect a bank account: A negative starting balance is passed to the constructor A negative interest rate is passed to the constructor A negative number is passed to the deposit method A negative number is passed to the withdraw method The amount passed to the withdraw method exceeds the account’s balance We can create exceptions that represent each of these error conditions Updated by L. Lilien

Creating Exception Classes Example: BankAccount.java NegativeStartingBalance.java AccountTest.java Updated by L. Lilien

++READ++ @exception Tag in Documentation Comments General format @exception ExceptionName Description The following rules apply The @exception tag in a method’s documentation comment must appear after the general description of the method The description can span several lines. It ends at the end of the documentation comment (the */ symbol) or at the beginning of another tag

12.3. Advanced File I/O: Binary Files, Random Access Files, and Object Serialization 12.3.A. Binary Files 12.3.B. Random Access Files ++OPTIONAL++ 12.3.C. Object Serialization © 2014 Leszek T. Lilien

12.3.A. Binary Files Data is stored in memory in the raw binary format Data can be stored in a file in the raw binary format Binary file = a file that contains binary data Binary files cannot be opened in a text editor (such as MS Word or Notepad) Storing data in its binary format is more efficient than storing it as text There are some types of data that should only be stored in its raw binary format Updated by L. Lilien

Binary Files – Writing/Creating Writing data to a binary file requires creating objects from the following classes: FileOutputStream To open a binary file Only basic functionality for writing bytes to the binary file DataOutputStream To write data of any primitive type or String objects to a binary file Cannot directly access a binary file Used in conjunction with a FileOutputStream object (the latter is connected to a binary file) – see the next page Updated by L. Lilien

Binary Files – Writing/Creating A DataOutputStream object is wrapped around a FileOutputStream object to write data to a binary file FileOutputStream fstream = new FileOutputStream("MyInfo.dat"); DataOutputStream outputFile = new DataOutputStream(fstream); These statements can combined into one new DataOutputStream( new FileOutputStream("MyInfo.dat")); BE CAREFUL: If the file that you are opening with the FileOutputStream object already exists, it will be erased and an empty file by the same name will be created Updated by L. Lilien

Binary Files – Writing/Creating Once the DataOutputStream object has been created, you can use it to write binary data to the file Example: WriteBinaryFile.java Updated by L. Lilien

Binary Files – Reading To open a binary file for input, you wrap a DataInputStream object around a FileInputStream object. FileInputStream fstream = new FileInputStream("MyInfo.dat"); DataInputStream inputFile = new DataInputStream(fstream); These two statements can be combined into one new DataInputStream( new FileInputStream("MyInfo.dat")); Updated by L. Lilien

Binary Files – Reading The FileInputStream constructor will throw a FileNotFoundException if the file named by the string argument cannot be found Once the DataInputStream object has been created, you can use it to read binary data from the file Example: ReadBinaryFile.java Updated by L. Lilien

Writing and Reading Strings To write a string to a binary file, use the DataOutputStream class’s writeUTF method writeUTF writes its String argument in a format known as UTF-8 encoding Just before writing the string, writeUTF writes a two-byte integer indicating the number of bytes that the string occupies Then, writeUTF writes the string’s characters in Unicode (UTF stands for Unicode Text Format) To read a string from a binary file, use the DataInputStream class’s readUTF method Updated by L. Lilien

Writing and Reading Strings To write a string to a binary file: String name = "Chloe"; outputFile.writeUTF(name); To read a string from a binary file: String name = inputFile.readUTF(); The readUTF method will correctly read a string only when the string was written with the writeUTF method Example: WriteUTF.java ReadUTF.java Updated by L. Lilien

Appending Data to Binary Files The FileOutputStream constructor takes an optional second argument : a boolean If the argument is true, the file will not be erased if it exists; new data will be appended to the end of the file If the argument is false, the file will be erased if it already exists FileOutputStream fstream = new FileOutputStream("MyInfo.dat", true); DataOutputStream outputFile = new DataOutputStream(fstream);

++OPTIONAL++ 12.3.B. Random Access Files Text files and the binary files previously shown use sequential file access. With sequential access: The first time data is read from the file, the data will be read from its beginning. As the reading continues, the file’s read position advances sequentially through the file’s contents. Sequential file access is useful in many circumstances. If the file is very large, locating data buried deep inside it can take a long time.

++OPTIONAL++ Random Access Files Java allows a program to perform random file access. In random file access, a program may immediately jump to any location in the file. To create and work with random access files in Java, you use the RandomAccessFile class. RandomAccessFile(String filename, String mode) filename: the name of the file. mode: a string indicating the mode in which you wish to use the file. "r" = reading "rw" = for reading and writing.

++OPTIONAL++ Random Access Files // Open a file for random reading. RandomAccessFile randomFile = new RandomAccessFile("MyData.dat", "r"); // Open a file for random reading and writing. RandomAccessFile randomFile = new RandomAccessFile("MyData.dat", "rw"); When opening a file in "r" mode where the file does not exist, a FileNotFoundException will be thrown. Opening a file in "r" mode and trying to write to it will throw an IOException. If you open an existing file in "rw" mode, it will not be deleted and the file’s existing content will be preserved.

++OPTIONAL++ Random Access Files Items in a sequential access file are accessed one after the other. Items in a random access file are accessed in any order. If you open a file in "rw" mode and the file does not exist, it will be created. A file that is opened or created with the RandomAccessFile class is treated as a binary file.

++OPTIONAL++ Random Access Files The RandomAccessFile class has: the same methods as the DataOutputStream class for writing data, and the same methods as the DataInputStream class for reading data. The RandomAccessFile class can be used to sequentially process a binary file. Example: WriteLetters.java

++OPTIONAL++ The File Pointer The RandomAccessFile class treats a file as a stream of bytes. The bytes are numbered: the first byte is byte 0. The last byte’s number is one less than the number of bytes in the file. These byte numbers are similar to an array’s subscripts, and are used to identify locations in the file. Internally, the RandomAccessFile class keeps a long integer value known as the file pointer.

++OPTIONAL++ The File Pointer The file pointer holds the byte number of a location in the file. When a file is first opened, the file pointer is set to 0. When an item is read from the file, it is read from the byte that the file pointer points to. Reading also causes the file pointer to advance to the byte just beyond the item that was read. If another item is immediately read, the reading will begin at that point in the file.

++OPTIONAL++ The File Pointer An EOFException is thrown when a read causes the file pointer to go beyond the size of the file. Writing also takes place at the location pointed to by the file pointer. If the file pointer points to the end of the file, data will be written to the end of the file. If the file pointer holds the number of a byte within the file, at a location where data is already stored, a write will overwrite the data at that point.

++OPTIONAL++ The File Pointer The RandomAccessFile class lets you move the file pointer. This allows data to be read and written at any byte location in the file. The seek method is used to move the file pointer. rndFile.seek(long position); The argument is the number of the byte that you want to move the file pointer to.

++OPTIONAL++ The File Pointer RandomAccessFile file = new RandomAccessFile("MyInfo.dat", "r"); file.seek(99); byte b = file.readByte(); Example: ReadRandomLetters.java

12.3.C. Object Serialization Java allows to serialize an object I.e., convert an object into a series of bytes that contain all object’s data If the object is set up properly, the other objects nested in it Iif any) are automatically serialized It is easy to save serialized objects into a file For later retrieval Updated by L. Lilien

Object Serialization For an object to be serialized, its class must implement the Serializable interface The Serializable interface has no methods or fields The Serializable interface is used only to let the Java compiler know that objects of the class might be serialized If a class contains nested objects (these other classes are fields of the enclosing object), classes for nested objects must also implement the Serializable interface Example: BankAccount2.java Updated by L. Lilien

Object Serialization The String class, as many others in the Java API, implements the Serializable interface Updated by L. Lilien

Object Serialization Example: Serialize an object and to write it to a file: FileOutputStream outStream = new FileOutputStream("Objects.dat"); ObjectOutputStream objectOutputFile = new ObjectOutputStream(outStream); BankAccount2 account = new BankAccount(25000.0); objectOutputFile.writeObject(account); ObjectOutputStream class’s writeObject method is used to serialize an object and write it to the file The method throws an IOException if an error occurs Updated by L. Lilien

Object Deserialization Object deserialization = reading a serialized object’s bytes from a file and reconstructing an object from them Example: Deserialize an object after reading it from a file FileInputStream inStream = new FileInputStream("Objects.dat"); ObjectInputStream objectInputFile = new ObjectInputStream(inStream); BankAccount2 account; account = (BankAccount2) objectInput File.readObject(); // cast to BankAccount2 is necessary! ObjectInputStream class’s readObject method is used to read an object from the file and deserialize it The method throws a number of different exceptions if an error occurs Updated by L. Lilien

Object Serialization/Deserialization Examples: SerializeObjects.java DeserializeObjects.java Updated by L. Lilien

The End © 2014 Leszek T. Lilien Updated by L. Lilien