Chapter 8: Exceptions and I/O Streams

Download Report

Transcript Chapter 8: Exceptions and I/O Streams

Chapter 8: Exceptions and I/O Streams
Presentation slides for
Java Software Solutions
Foundations of Program Design
Third Edition
by John Lewis and William Loftus
Java Software Solutions is published by Addison-Wesley
Presentation slides are copyright 2002 by John Lewis and William Loftus. All rights reserved.
Instructors using the textbook may use and modify these slides for pedagogical purposes.
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 de-serialization
• more GUI components
• animations
2
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
3
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
4
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
(Definition of a stack …)
 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)
5
The try Statement
See Try Statement syntax directed graph -- page 450
 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 (see explanation & test data results on
pages 451 - 452)
6
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
7
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) -- driver
 See ExceptionScope.java (page 456)
 on screen
Description of method activations using a stack. Stack trace explanation.
Levels 3 and 2 do not catch & handle the exceptions.
(draw stack)
Control passed back to level 1 which handles the exceptions.
Programmer must pick best place to catch and handle exceptions.
Choice may be not to catch and let program terminate.
8
Object
Exception Class Hierarchy
Throwable
LinkageError
RunTimeException
ThreadDeath
ArithmeticException
VirtualMachineError
IndexOutOfBoundsException
AWTError
NullPointerException
IllegalAccessException
Figure 8.1, page 458
Read 3, bottom pg. 454
NoSuchMethodException
ClassNotFoundException
(AWT – Abstract Windowing Toolkit)
unchecked exceptions
(generally should not be caught)
Exception
Error
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) – driver
 See OutOfRangeException.java (page 460)
10
OutOfRangeException.java
Whether or not to use
an exception, a conditional, or a loop are
are important design decisions.
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 complain if a checked exception is not handled
appropriately
 See throws clause in main method of CreatingExceptions program (pg 459)
- throws clause indicates program may throw an OutOfRangeException
– throws clause required because OutOfRangeException derived from
Exception class which makes it a checked exception
12
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
(see Exception class hierarchy – pg. 458)
 Errors are similar to RuntimeException and its
descendants
• Errors should not be caught
Why?
Unrecoverable !
• Errors do not require a throws clause
HW 8.1 & HW 8.3
 due
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
What does this mean?
Diagrams on board of –
-- disk drives with files
-- printers receiving data streams from file
-- memory with conceptual records from a file
-- with multiple data streams from several files
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
(16-bit Unicode characters)
• Others assume that the data consists of raw bytes of binary information
(8-bit bytes of raw binary data – i.e., sounds or images or robot
commands)
• Some classes provide means of manipulating the data:
- by buffering (holding data chunks for later processing)
- by interpreting and/or converting data to sound, video, robotic motion,
etc.
I/O Streams
 An I/O stream is also either a
• data stream, which acts as either a source or destination
• processing stream, which alters or manipulates the basic data in
the stream
Input Streams
or
Output Streams
Figure 8.2 , pg. 462
Dissect “cube”
 8 combinations 
Character Streams
or
Byte Streams
Data
Processing
or
Streams
Streams
Character Streams 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
• They may be 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
See Java I/O class hierarchy - figure 8.3, p. 463
The Java I/O Class Hierarchy
Figure 8.3 , pg. 463  make notes in your text
Java I/O class hierarchy
 note partition of byte stream and character stream
 note four primary I/O class hierarchies
Byte Steam
Character Steam
InputStream
OutputStream
Reader
Writer
Data Streams vs. Processing Streams
 A data stream represents a particular source or destination
stream 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
• processing stream may convert the data from one format to another
i.e., numeric character string to float ( ‘1124.56’ )
• processing stream may buffer the stream
into groups for transmission over a network or to a printer ( or other
purposes) Diagram with printer receiving buffered data (see on board)
Why buffer data going to a printer?
The IOException Class
 Operations performed by the I/O classes may throw an
IOException (again see fig. 8.3 – pg. 463)
What could these exceptions be?
• A file intended for reading or updated 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 (non-compatible
data types – i.e., char when expecting int, etc.
 An IOException is a checked exception
(fig. 8.1, pg. 458)
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
(These references are declared both private and static –
they may be accessed directly through the System class.)
Standard I/O
 PrintStream objects automatically have print and
println methods defined for them
 The PrintWriter class is needed for advanced inter nationalization and error checking
The Keyboard Class
 The Keyboard class was written by the authors of your
textbook to facilitate reading data from standard input as you
began your study of Java
 Now we can examine the processing of the Keyboard class
in more detail
 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
(int, float, String, etc.)
• 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
(see hierarchy, pg. 463 )
 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 so if an
IOException is thrown it may be handled gracefully
 The Keyboard class uses a StringTokenizer object to extract tokens
 The Keyboard class performs type conversions as needed
Look at these again – (read bottom of pg 466 )
InputStreamReader isr = new InputStreamReader(System.in)
BufferedReader stdin = new BufferedReader (isr);
Example of an input string accessed by Keyboard class
String line = Keyboard.readString( );
Tokens could be words “in”, “Casablanca”, “Humphrey”, “700,000”, etc.
“700,000” could be converted to type int 700000
Reading Text Files
 Information can be read from and written to text files on disk by declaring
and using the correct I/O streams
 The FileReader class represents an input file containing character
data
(Java I/O class hierarchy – pg. 463)
 The FileReader and BufferedReader classes together create a
convenient text file input stream
(see file & buffer diagrams on board)
 See CheckInventory.java (page 468) – driver
 See InventoryItem.java (page 470)
see data & run
-- discuss records from inventory.dat file & explain record layout
-- discuss “hidden” characters
Writing 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)
Note random data output example for TestData.java
– see bottom page 473 and top of page 474.
TestData.java
 Use of BufferWriter not absolutely necessary but makes
processing more efficient. (consider accessing disc)
( file & buffer diagrams on board )
 All IOExceptions are checked exceptions so we must include
"throws" clause on method header. For every program we
must consider how to handle exceptions that may be thrown.
VERY important when dealing with I/O.
 I/O may present many problems which may not be foreseen.
What may problems be?
 Output streams (output data files) should be closed explicitly –
to insure data is retained.
Old fashion terms you need to know
Terms used to discuss files
(used prior to Object-Oriented technology)
File0
Record0
Field0 Field1 Field2 … FieldN
Record1
Field0 Field1 Field2 … FieldN
Record2
Field0 Field1 Field2 … FieldN
...
RecordN
Field0 Field1 Field2 … FieldN
Review
 inventoryA.dat – what is REALLY in this file?
What does a program such as NotePad put in the file?
 Reading and writing text files using character stream and data stream
• Character streams –used to manage 16bit-Unicode characters –series of characters
• Byte stream – 8-bit bytes of raw binary data – interpretation depends …
• Data steams – represent source or destination stream
• Processing streams or filtering streams – manipulate data (converting, buffering)
character stream (as tokens)  Spoke 132 0.32 Wrap 58 1.92 Brace 25 1.75 …
byte stream  Êþº¾ . M
$ % &
$ '
( ) * +
*
, -…
(Unicode character representation of raw binary data from TestData.class object code)
 Must interpret byte streams based on what they are - .dat, .xls, .doc, .class, etc
Object Serialization
 Serialize – process of converting an object into a linear series of
bytes so it can be saved to a file or sent across a network
( remember byte stream from TestData.class
Êþº¾ . M $ % & $ ' ( ) * + * … )
 Object serialization is the mechanism for saving an object, and
its current state, so that it can be preserved and used again in
another program
 The idea that an object can “live” beyond the program
execution that created it is called persistence
data that comprises the object is stored in a file
Object Serialization
 The processing stream that handles the byte data has the object definition
intelligence.
 Object serialization is accomplished using the Serializable interface
(has no methods - tells compiler this object may be serialized)
and
the ObjectOutputStream and ObjectInputStream classes
(processing streams that are wrapped around OutputStream
or InputStream)
 ObjectOutputStream and ObjectInputStream are processing
streams that handle byte streams
see Java I/O class hierarchy fig.8.1 top pg.463
processing stream / byte stream
process streams – used to process objects
I.e., ObjectInputStream & ObjectOutputStream
byte steams – represent 8-bit bytes of raw binary data
Êþº¾ . M $ % & $ ' ( ) * + * …
(class objects compiled code)
countries objects
in main memory
Êþº¾ . M
$ % &
$ '
( ) * +*
ObjectOutputStream
(outStream)
TestData.class
outStream object in WriteCountryInfo.java
serialized
countries
objects
Object Serialization
 The writeObject method is used to serialize an object
 The readObject method is used to deserialize an object
 ObjectOutputStream and ObjectInputStream are processing
streams that must be wrapped around an OutputStream or an
InputStream
 Serialization takes into account any other objects that are
referenced by an object being serialized, saving them too
 See WriteCountryInfo.java (page 475)
 See CountryInfo.java (page 477)
Object Deserialization
Let’s reverse the serialization process – re-load the object
The readObject method is used to deserialize an object
What does deserialize mean?
ObjectInputStream are processing streams that must be
wrapped around an InputStream
countries objects
in main memory
Êþº¾ . M
$ % &
$ '
( ) * +*
ObjectInputStream
(inStream)
TestData.class
inStream object in ReadCountryInfo.java
serialized
countries
objects
Object Deserialization
Reverse the serialization process – re-load the object
The readObject method is used to deserialize an object
See ReadCountryInfo.java (page 479)
Examine “countries.dat” file
Serialization – additional references
Serialization automatically handles referenced objects if
interface is provided.
Car
Chassis
Engine
Driver
Etc.
For serialization to work each class must implement a
Serializable interface – i.e.
public class Car implements Serializable;
public class Engine implements Serializable;
etc.
public class Driver implements Serializable;
Serialization – additional references
 Car class serialization occurs and references Engine
class, Engine class serialization occurs automatically
(Engine class must also implement Serializable
interface)– etc. for other sub-classes.)
also
 The ArrayList class implements the Serializable interface,
permitting an entire list of objects to be stored in one
operation
Does not have to use a loop to iterate thought the
storing operation.
The transient Modifier
 When we serialize an object, sometimes we prefer to exclude a
particular piece of information such as a password, etc.
 The reserved word transient modifies the declaration of a
variable so that it will not be included in the byte stream when
the object is serialized
 Example 
private transient int secretInt;
Note: a private visibility alone will not insure security – once
serialized could be read and accessed by unfriendly person
“secretInt” added to CountryInfo –
ReadCountryInfo returned 0 when deserialized
the objects.
Review – lab final exam
Review and know how the programs WriteCountryInfo.java,
ReadCountryInfo. Java, and CountryInfo.java work.
Know how to modify code of this type to serialize and
deserialize objects.
BE SURE TO BRING YOUR JAVA SOURCE CODE CD TO
THE FINAL EXAM.
Also, bring an envelop and BLANK diskette to the lab final
exam.
Stop - Chapter 8
Files and GUIs
 GUIs sometimes involve external files
 A file chooser is a specialized dialog box from the
JFileChooser class
 A file chooser allows the user to browse a disk or other
storage device to select a file
 See DisplayFile.java (page xxx)
DisplayFile.java
More GUI Components
 A text area component is defined by the JTextFile
class
 A color chooser is a component from the
JColorChooser class that allows a user to choose a
color
 See DisplayColor.java (page xxx)
DisplayColor.java
More GUI Components
 An ImageIcon object represents an image that is used
in a label
 ImageIcon objects use either JPEG or GIF images
 See LabelDemo.java (page xxx)
Key Events
 A key event is generated when a keyboard key is
pressed
 See Direction.java (page xxx)
 See DirectionPanel.java (page xxx)
Direction.java
DirectionPanel.java
Methods of the KeyListener
Interface
 (Figure 8.4 here)
 The component that generates key events is said to have
keyboard focus
Animations
 An animation is a series of images that gives the
apperance of movement
 To create the illusion of movement, we use the Timer
class to change the scene after an appropriate delay
 A timer object from the Timer class of the
javax.swing package is like a GUI component, even
though it has no visual representation
 A Timer object generates an action event used to control
an animation
Some Methods of the Timer Class
 (Figure 8.5 here)
Animations
 See Rebound.java (page xxx)
 See ReboundPanel.java (page xxx)
Rebound.java
ReboundPanel.java
Summary
 Chapter 8 has focused 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