Chapter 11 Exceptions and Input/Output Operations.

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

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.
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
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.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
COMP 121 Week 5: Exceptions and Exception Handling.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Exception handling Dealing with life’s little surprises.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Lecture 7 File I/O (and a little bit about exceptions)‏
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.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Files and Streams CS 21a Chapter 11 of Horstmann.
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.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Exceptions and Input/Output Operations
Java Software Solutions Foundations of Program Design Sixth Edition
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
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.
Java Programming: Guided Learning with Early Objects
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Java I/O Writing and Reading Objects to File Serialization.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Object Persistence and Object serialization CSNB534 Asma Shakil.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
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.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
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.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
Java Programming Review (Part II) Enterprise Systems Programming.
Exceptions and Assertions Chapter 15 – CSCI 1302.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
CS 116 Object Oriented Programming II Lecture 11 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
CS 116 Object Oriented Programming II Lecture 10 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
I/O Basics.
CS 116 Object Oriented Programming II
Exception Handling Chapter 9.
Exceptions & exception handling
Exceptions & exception handling
CSS 161: Fundamentals of Computing
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Presentation transcript:

Chapter 11 Exceptions and Input/Output Operations

Topics Exception Handling –Using try and catch Blocks –Catching Multiple Exceptions –User-Defined Exceptions The java.io Package Parsing a String using Scanner Reading Text Files Using Scanner Writing and Appending to Text Files Reading Structured Text Files Reading and Writing Objects to a File

Exceptions Illegal operations at run time can generate an exception. For example, we have seen these exceptions: –ArithmeticException –NullPointerException –InputMismatchException –NumberFormatException –ArrayIndexOutOfBoundsException

Handling Exceptions In a program without a Graphical User Interface, exceptions cause the program to terminate. With this code that attempts to read an int: String s = JOptionPane.showInputDialog( null, "Enter an integer" ); int n = Integer.parseInt( s ); If the user enters a, we get a NumberFormatException: See Example 11.1 DialogBoxInput.java

Handling Exceptions We don't want invalid user input to terminate our programs! It is better to detect the problem and reprompt the user for the input. Java allows us to intercept and handle some of these exceptions using try and catch blocks. –Inside the try block, we put the code that might generate an exception. –Inside catch blocks, we put the code to handle any exceptions that could be generated.

Minimum try/catch Syntax try { // code that might generate an exception } catch( ExceptionClass exceptionObjRef ) { // code to recover from the exception } If an exception occurs in the try block, control jumps immediately to the catch block. No further instructions in the try block are executed. If no exceptions are generated in the try block, the catch block is not executed.

The ExceptionClass parameter to the catch block can be any of these exceptions. Exception Class Hierarchy The Exception class, RuntimeException class, and their subclasses are in the java.lang package. The IOException class and its subclasses are in the java.io package.

Checked and Unchecked Exceptions Java distinguishes between two types of exceptions: Unchecked exceptions are those that are subclasses of Error or RuntimeException –It is not mandatory to use try and catch blocks to handle these exceptions. Checked exceptions are any other exceptions. –Code that might generate a checked exception must be put inside a try block or the method must acknowledge that the exception may occur by using a throws clause in the method header. Otherwise, the compiler will generate an error.

Exception Class Methods Inside the catch block, you can call any of these methods of the Exception class: Return valueMethod name and argument list StringgetMessage( ) returns a message indicating the cause of the exception StringtoString( ) returns a String containing the exception class name and a message indicating the cause of the exception voidprintStackTrace( ) prints the line number of the code that caused the exception along with the sequence of method calls leading up to the exception

Catching a NumberFormatException int n = 0; // declare and initialize variable String s = JOptionPane.showInputDialog( null, "Enter an integer" ); try { n = Integer.parseInt( s ); System.out.println( "You entered " + n ); } catch ( NumberFormatException nfe ) { System.out.println( "Incompatible data." ); } See Example 11.2 DialogBoxInput.java

Initializing Variables for try/catch Notice that we declare and initialize the input variable (n) before we enter the try block. If we do not initialize the variable and then try to access it after the try/catch blocks, we will receive the following compiler error: variable n might not have been initialized The error indicates that the only place where n is assigned a value is in the try block. If an exception occurs, the try block will be interrupted and we might not ever assign n a value. Initializing the value before entering the try block solves this problem.

Recovering From an Exception The previous code simply printed a message when the exception occurred. To continue processing, reprompt the user for good input by putting the try and catch blocks inside a do/while loop, as shown on the next slide -> See Example 11.3 DialogBoxInput.java

int n = 0; boolean goodInput = false; // flag variable String s = JOptionPane.showInputDialog( null, "Enter an integer" ); do { try { n = Integer.parseInt( s ); goodInput = true; // executed if no exception } catch ( NumberFormatException nfe ) { s = JOptionPane.showInputDialog( null, s + " is not an integer. " + "Enter an integer" ); } } while ( ! goodInput );

Write code to catch and handle exceptions generated by invalid user input. Always try to write code that is user-friendly. Although the methods of the Exception class are good debugging tools, they are not necessarily appropriate to use in the final version of a program. SOFTWARE ENGINEERING TIP

Catching Multiple Exceptions If the code in the try block might generate multiple, different exceptions, we can provide multiple catch blocks to handle each possible exception. When an exception is generated, the JVM searches the catch blocks in order. The first catch block with a parameter that matches the exception thrown will execute; any remaining catch blocks will be skipped.

catch Block Order An exception will match a catch block with a parameter that names any of its superclasses. –For example, a NumberFormatException will match a catch block with a RuntimeException parameter. –All exceptions will match a catch block with an Exception parameter. Thus, when coding several catch blocks, arrange the catch blocks with the specialized exceptions first, followed by more general exceptions.

The finally Block Optionally, you can follow the catch blocks with a finally block. The finally block will be executed whether or not an exception occurs. Thus: –if an exception occurs, the finally block will be executed when the appropriate catch block finishes executing. –if no exception occurs, the finally block will be executed when the try block finishes. For example, a finally block might be used to close an open file. We demonstrate this later.

Full try/catch/finally Syntax try { // code that might generate an exception } catch( Exception1Class e1 ) { // code to handle an Exception1Class exception } … catch( ExceptionNClass eN ) { // code to handle an ExceptionNClass exception } finally { // code to execute whether or not an exception occurs }

Catching Multiple Exceptions We can write a program that catches several exceptions. For example, for a division operation, we can prompt the user for a divisor. –If the input is not an integer, we catch the NumberFormatException and reprompt the user with an appropriate message. –If the input is 0, we catch an ArithmeticException when we attempt to divide by 0, and reprompt the user with an appropriate message. See Example 11.4 Divider.java

User-Defined Exceptions We can design our own exception class. Suppose we want to design a class encapsulating addresses ( Address class). –For simplicity, we say that a legal address is a String containing character. Our Address constructor will throw an exception if its address argument is illegal. To do this, we design an exception class named Illegal Exception.

User-Defined Exception Java has an IllegalArgumentException class, so our Illegal Exception class can be a subclass of the IllegalArgumentException class. By extending the IllegalArgumentException class: –we inherit the functionality of an exception class, which simplifies our coding of the exception –we can easily associate a specific error message with the exception

Extending an Existing Exception We need to code only the constructor, which accepts the error message as a String. General pattern: public class ExceptionName extends ExistingExceptionClassName { public ExceptionName( String message ) { super( message ); } See Example 11.5 Illegal Exception.java

Throwing an Exception The pattern for a method that throws a user-defined exception is: accessModifier returnType methodName( parameters ) throws ExceptionName { if ( parameter list is legal ) process the parameter list else throw new ExceptionName( "Message here" ); } The message passed to the constructor identifies the error detected. In a client's catch block, the getMessage method retrieves that message. See Examples Address.java & Checker.java

Selected Input Classes in the java.io Package ClassDescription InputStream Abstract superclass representing a stream of raw bytes FileInputStream Input stream to read raw bytes of data from files ObjectInputStream Class to read/recover objects from a file written using ObjectOutputStream

Hierarchy for Input Classes

Selected java.io Output Classes ClassDescription Writer Abstract superclass for output classes OutputStream Abstract superclass representing an output stream of raw bytes PrintWriter Prints basic data types, Strings, and objects FileOutputStream Output stream for writing raw bytes of data to files ObjectOutputStream Class to write objects to a file

Hierarchy for Output Classes

Reading Text Files In Chapter 6, we read a text file by associating a Scanner object with a File object: Scanner file = new Scanner( new File( “filename.txt” ) ); We added the throws IOException clause to main to avoid handling exceptions that may occur. public static void main( String [] args ) throws IOException But when the file wasn’t found, a FileNotFoundException occurred; the user was given an unfriendly message; and the program terminated. Now that we know how to catch exceptions, we can intercept the FileNotFoundException and give the user a meaningful message.

Opening and Closing an InputStream When we construct an input stream or output stream object, the JVM associates the file name, standard input stream, or standard output stream with our object. This is opening the file. When we are finished with a file, we optionally call the close method to release the resources associated with the file. Return valueMethod name and argument list voidclose( ) releases resources associated with an open input stream. Throws an IOException.

Opening and Closing Standard Streams The standard input stream (System.in), the standard output stream (System.out), and the standard error stream (System.err) are open when the program begins. They are intended to stay open and should not be closed.

Calling the close method is optional. When the program finishes executing, all the resources of any unclosed files are released. It is good practice to call the close method, however, especially if you will be opening a number of files (or opening the same file multiple times.) Do not close the standard input, output, or error devices, however. They are intended to remain open. SOFTWARE ENGINEERING TIP

Exceptions While Reading from a File We can catch this exception: FileNotFoundException thrown by the Scanner constructor if the filename is not found when opening the file We do not expect these exceptions to occur, so we will catch them as subclasses of IOException, and print the stack trace. InputMismatchException if the input does not match the expected data type. (The next method does not throw this exception, so we don’t need to catch this exception). NoSuchElementException if we attempt to read beyond the end of the file. IllegalStateException if we attempt to read after calling the close method. See Example 11.8 ReadTextFile.java

Writing to Text Files Several situations can exist: –the file does not exist –the file exists and we want to replace the current contents –the file exists and we want to append to the current contents We specify whether we want to replace the contents or append to the current contents when we construct our FileOutputStream object.

Constructors for Writing to Text Files ClassConstructor FileOutputStreamFileOutputStream( String filename, boolean mode ) constructs a FileOutputStream object from a String representing the name of a file. If the file does not exist, it is created. If mode is false, the current contents of the file, if any, will be replaced. If mode is true, writing will append data to the end of the file. Throws a FileNotFoundException. PrintWriterPrintWriter( OutputStream os ) constructs a PrintWriter object from an OutputStream object

Methods of the PrintWriter Class See Example 11.9 WriteGradeFile.java and Example AppendGradeFile.java Return valueMethod name and argument list void Void void print( int i ) print( double d ) print( String s ) … println( int i ) println( double d ) println( String s ) writes the argument to the text file voidclose( ) releases resources allocated to the PrintWriter object.

Reading Structured Text Files Some text files are organized into lines that represent a record — a set of data values containing information about an item. The data values are separated by one or more delimiters; that is, a special character or characters that separate one value from the next. As we read the file, we need to parse each line; that is, separate the line into the individual data values called tokens.

Example An airline company could store data in a file where each line represents a flight segment containing the following data: –flight number –origin airport –destination airport –number of passengers –average ticket price Such a file could contain the following data : AA123,BWI,SFO,235,239.5 AA200,BOS,JFK,150,89.3 … In this case, the delimiter is a comma.

Using Scanner to Parse Strings The Scanner constructor below accepts a String. We can use any of the Scanner next methods to read tokens from the String. We can use any of the Scanner hasNext methods to determine whether more tokens are available to be read. The default delimiters are the white space characters (space, newline, tab, etc.). Constructor name and argument list Scanner( String source ) constructs a Scanner object that produces tokens from the specified String

Using Scanner to Parse Strings To specify different delimiters, call useDelimiter method: pattern represents a regular expression against which to match sequences of characters using standard characters as well as meta-characters, which have special meanings. We can specify a delimiter consisting of a single character or multiple specific characters as a simple String argument. See Example UsingScannerToParseAString.java Return ValueMethod name and argument list ScanneruseDelimiter( String pattern )

Example The file flight.txt contains the following comma-separated flight data on each line: flight number, origin airport, destination airport, number of passengers, average ticket price The FlightRecord class defines instance variables for each flight data value The ReadFlights class reads data from flights.txt, instantiates FlightRecord objects, and adds them to an ArrayList. See Examples FlightRecord.java and Example ReadFlights.java

Reading and Writing Objects Java also supports writing objects to a file and reading them as objects. This is convenient for two reasons: –We can write these objects directly to a file without having to convert the objects to primitive data types or Strings. –We can read the objects directly from a file, without having to read Strings and convert these Strings to primitive data types in order to instantiate objects. To read objects from a file, the objects must have been written to that file as objects.

Writing Objects to a File To write an object to a file, its class must implement the Serializable interface, which indicates that: –the object can be converted to a byte stream to be written to a file –that byte stream can be converted back into a copy of the object when read from the file. The Serializable interface has no methods to implement. All we need to do is: – import the java.io.Serializable interface –add implements Serializable to the class header

The ObjectOutputStream Class The ObjectOutputStream class, coupled with the FileOutputStream class, provide the functionality to write objects to a file. The ObjectOutputStream class provides a convenient way to write objects to a file. –Its writeObject method takes one argument: the object to be written.

Constructors for Writing Objects ClassConstructor FileOutputStreamFileOutputStream( String filename, boolean mode ) creates a FileOutputStream object from a String representing the name of a file. If the file does not exist, it is created. If mode is false, the current contents of the file, if any, will be replaced. If mode is true, writing will append data to the end of the file. Throws a FileNotFoundException. ObjectOutputStreamObjectOutputStream( OutputStream out ) creates an ObjectOutputStream that writes to the OutputStream out. Throws an IOException.

The writeObject Method See Examples FlightRecord2.java and Example WritingObjects.java Return valueMethod name and argument list voidwriteObject( Object o ) writes the object argument to a file. That object must be an instance of a class that implements the Serializable interface. Otherwise, a run-time exception will be generated. Throws an IOException.

Omitting Data from the File The writeObject method does not write any object fields declared to be static or transient. You can declare a field as transient if you can easily reproduce its value or if its value is 0. Syntax to declare a field as transient: accessModifier transient dataType fieldName Example : private transient double totalRevenue;

To save disk space when writing to an object file, declare the class's fields as static or transient, where appropriate. SOFTWARE ENGINEERING TIP

Reading Objects from a File The ObjectInputStream class, coupled with FileInputStream, provide the functionality to read objects from a file. The readObject method of the ObjectInputStream class is designed to read objects from a file. Because the readObject method returns a generic Object, we must type cast the returned object to the appropriate class. When the end of the file is reached, the readObject method throws an EOFException, so we detect the end of the file when we catch that exception.

Constructors for Reading Objects ClassConstructor FileInputStreamFileInputStream( String filename ) constructs a FileInputStream object from a String representing the name of a file. Throws a FileNotFoundException. ObjectInputStreamObjectInputStream( InputStream in ) creates an ObjectInputStream from the InputStream in. Throws an IOException.

The readObject Method See Example ReadingObjects.java -- we detect reaching the end of the file in the catch block for EOFException –we use a finally block to close the file. Return valueMethod name and argument list ObjectreadObject( ) reads the next object and returns it. The object must be an instance of a class that implements the Serializable interface. When the end of the file is reached, an EOFException is thrown. Also throws an IOException and ClassNotFoundException