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,

Slides:



Advertisements
Similar presentations
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Advertisements

CS102--Object Oriented Programming
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
1 Chapter 10: Exceptions and I/O Streams Original Slides by John Lewis and William Loftus Modified significantly by Bob Roggio.
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.
ELC 310 Day 21. © 2004 Pearson Addison-Wesley. All rights reserved10-2 Agenda Questions? Capstone Proposals Overdue  4 Submitted  3 Accepted, 1 in negotiations.
10-1 Writing to a Text File When a text file is opened in this way, a FileNotFoundException can be thrown – In this context it actually means that the.
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.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 8 Overview – Learn to use try catch blocks – Learn to use streams – Learn to use text files.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
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,
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting.
Java Software Solutions Foundations of Program Design Sixth Edition
Preventing and Correcting Errors
1 Advanced Flow of Control - Introduction - zTwo additional mechanisms for controlling process execution are exceptions and threads zChapter 14 focuses.
CIS 270—Application Development II Chapter 13—Exception Handling.
10-1 Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
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 Software Solutions Lewis and Loftus Chapter 14 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Advanced Flow of Control --
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
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.
Exceptions Chapter 10 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
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.
© 2004 Pearson Addison-Wesley. All rights reserved April 24, 2006 Exceptions (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING 2006.
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.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
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.
1 Chapter 10: Exceptions and I/O Streams Original Slides by John Lewis and William Loftus Modified significantly by Bob Roggio, July 2007.
Chapter 10 Exceptions 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
1 Exceptions Exception handling – Exception Indication of problem during execution – E.g., divide by zero – Chained exceptions Uses of exception handling.
© 2004 Pearson Addison-Wesley. All rights reserved December 5, 2007 I/O Exceptions & Working with Files ComS 207: Programming I (in Java) Iowa State University,
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
CSE 1201 Object Oriented Programming
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Streams & File Input/Output (I/O)
10 Exceptions Software Solutions Lewis & Loftus java 5TH EDITION
I/O Streams A stream is a sequence of bytes that flows from a source to a destination In a program, we read information from an input stream and write.
I/O Basics.
04/14/14 Exceptions.
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
CSS 161: Fundamentals of Computing
Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.
Abdulmotaleb El Saddik University of Ottawa
I/O Streams A stream is a sequence of bytes that flow from a source to a destination In a program, we read information from an input stream and write information.
Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Exceptions (part 2) December 3, 2007 ComS 207: Programming I (in Java)
I/O Exceptions & Working with Files
Chapter 11 Exceptions Java Software Solutions
Chapter 8: Exceptions and I/O Streams
Presentation transcript:

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, and used with permission. All rights reserved.

2 Exceptions and I/O Streams  Now we can explore two related topics further: exceptions and input/output streams  Chapter 8 focuses on: the try-catch statement exception propagation creating and throwing exceptions types of I/O streams Keyboard class processing reading and writing text files object serialization and deserialization more GUI components animations

3 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown by a program, and may be caught and handled by another part of the program  A program can be separated into a normal execution flow and an exception execution flow  An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught

4 Exception Handling  Java has a predefined set of exceptions and errors that can occur during execution  A program can deal with an exception in one of three ways: ignore it handle it where it occurs handle it an another place in the program  The manner in which an exception is processed is an important design consideration

5 Exception Handling  If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message  The message includes a call stack trace that indicates the line on which the exception occurred  The call stack trace also shows the method call trail that lead to the attempted execution of the offending line The getMessage method returns a string explaining why the exception was thrown The printStackTrace method prints the call stack trace  See Zero.java (page 449) Zero.java

6 The try Statement  To process an exception when it occurs, the line that throws the exception is executed within a try block  A try block is followed by one or more catch clauses, which contain code to process an exception  Each catch clause has an associated exception type and is called an exception handler  When an exception occurs, processing continues at the first catch clause that matches the exception type  See ProductCodes.java (page 451) ProductCodes.java

7 The finally Clause  A try statement can have an optional clause following the catch clauses, designated by the reserved word finally  The statements in the finally clause always are executed  If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete  If an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete

8 Exception Propagation  An exception can be handled at a higher level if it is not appropriate to handle it where it occurs  Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the level of the main method  A try block that contains a call to a method in which an exception is thrown can be used to catch that exception  See Propagation.java (page 455) Propagation.java  See ExceptionScope.java (page 456) ExceptionScope.java

9 The throw Statement  A programmer can define an exception by extending the Exception class or one of its descendants  Exceptions are thrown using the throw statement  Usually a throw statement is nested inside an if statement that evaluates the condition to see if the exception should be thrown  See CreatingExceptions.java (page 459) CreatingExceptions.java  See OutOfRangeException.java (page 460) OutOfRangeException.java

10 Checked Exceptions  An exception is either checked or unchecked  A checked exception either must be caught by a method, or must be listed in the throws clause of any method that may throw or propagate it  A throws clause is appended to the method header  The compiler will issue an error if a checked exception is not handled appropriately

Unchecked Exceptions  An unchecked exception does not require explicit handling, though it could be processed that way  The only unchecked exceptions in Java are objects of type RuntimeException or any of its descendants  Errors are similar to RuntimeException and its descendants Errors should not be caught Errors to not require a throws clause

I/O Streams  A stream is a sequence of bytes that flow from a source to a destination  In a program, we read information from an input stream and write information to an output stream  A program can manage multiple streams simultaneously

I/O Streams  The java.io package contains many classes that allow us to define various streams with particular characteristics  Some classes assume that the data consists of characters  Others assume that the data consists of raw bytes of binary information  Streams can be further subdivided as follows: data stream, which acts as either a source or destination processing stream, which alters or manipulates the basic data in the stream

I/O Streams Character Streams Byte Streams Data Streams Processing Streams Input Streams Output Streams

Character vs. Byte Streams  A character stream manages 16-bit Unicode characters  A byte stream manages 8-bit bytes of raw binary data A program must determine how to interpret and use the bytes in a byte stream Typically they are used to read and write sounds and images  The InputStream and OutputStream classes (and their descendants) represent byte streams  The Reader and Writer classes (and their descendants) represent character streams

Data vs. Processing Streams  A data stream represents a particular source or destination such as a string in memory or a file on disk  A processing stream (also called a filtering stream) manipulates the data in the stream It may convert the data from one format to another It may buffer the stream

The IOException Class  Operations performed by the I/O classes may throw an IOException A file intended for reading or writing might not exist Even if the file exists, a program may not be able to find it The file might not contain the kind of data we expect  An IOException is a checked exception

Standard I/O  There are three standard I/O streams: standard input – defined by System.in standard output – defined by System.out standard error – defined by System.err  System.in typically represents keyboard input  System.out and System.err typically represent a particular window on the monitor screen  We use System.out when we execute println statements

Standard I/O  PrintStream objects automatically have print and println methods defined for them  The PrintWriter class is needed for advanced internationalization and error checking

The Keyboard Class  The Keyboard class was written by the authors of your textbook to facilitate reading data from standard input  Chapter 5 explored some of the underlying issues  Now we can examine the processing of the Keyboard class further  The Keyboard class: declares a useful standard input stream handles I/O exceptions that may be thrown parses input lines into tokens converts an input value into the expected type handles conversion problems

The Keyboard Class  The Keyboard class declares the following input stream: InputStreamReader isr = new InputStreamReader (System.in) BufferedReader stdin = new BufferedReader (isr);  The InputStreamReader object converts the original byte stream into a character stream  The BufferedReader object allows us to use the readLine method to get an entire line of input

The Keyboard Class  Each invocation or readLine is performed inside a try block  The Keyboard class uses a StringTokenizer object to extract tokens  The Keyboard class performs type conversions as needed

Text Files  Information can be read from and written to text files by declaring and using the correct I/O streams  The FileReader class represents an input file containing character data  The FileReader and BufferedReader classes together create a convenient text file output stream  See CheckInventory.java (page 468) CheckInventory.java  See InventoryItem.java (page 470) InventoryItem.java

File I/O and Java IDE’s  Unfortunately, Java is funny about where it looks for files. From the previous example, where file is the name of a file to be read, say, “inventory.dat”: FileReader fr = new FileReader (file);  Unless the file name is a complete pathname (e.g. “C:/temp/inventory.dat”) Java looks for the file in the directory where Java is invoked. If Java has been invoked explicitly from the command line, while in the directory containing the file, everything is okay.  Most IDE’s, however, run Java from the directory containing the java.exe executable. And, of course, your data is probably not there!  The same problem exists where running applets downloaded from the web.

Telling Java Whence a File  We need to tell Java of an alternate place to find data files. In particular, we want Java to look in the same directory as where it found the.class files.  Every class has an associated ClassLoader object, which contains this information. If item is an object of your own design, then item.getClass().getClassLoader()  obtains the corresponding class loader. Now we can ask the loader to obtain a file from the same directory as item ’s class: URL url = item.getClass().getClassLoader.getResource(file)

Using a Resource (a File)  To use the URL, we use code very much like in our original attempt: BufferedReader inFile = new BufferedReader( new InputStreamReader(url.openStream()));

Text Files  The FileWriter class represents a text output file, but with minimal support for manipulating data  Therefore, the PrintWriter class provides print and println methods  See TestData.java (page 472) TestData.java  Output streams should be closed explicitly