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 deserialization
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
 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
 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)
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)
 See ExceptionScope.java (page 456)
8
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)
 See OutOfRangeException.java (page 460)
9
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
10
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
Input Streams
Output Streams
Character
Streams
Byte
Streams
Data
Streams
Processing
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)
 See InventoryItem.java (page 470)
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)
 Output streams should be closed explicitly
Object Serialization
 Object serialization is the mechanism for saving an object,
and its current state, so that it can be used again in
another program
 The idea that an object can “live” beyond the program
execution that created it is called persistence
 Object serialization is accomplished using the
Serializable interface and the ObjectOutputStream
and ObjectInputStream classes
 The writeObject method is used to serialize an object
 The readObject method is used to deserialize an object
Object Serialization
 ObjectOutputStream and ObjectInputStream are
processing streams that must be wrapped around an
OutputStream or an InputStream
 See WriteCountryInfo.java (page 475)
 See CountryInfo.java (page 477)
 Once serialized, the objects can be read again into
another program
 See ReadCountryInfo.java (page 479)
Object Serialization
 Serialization takes into account any other objects that are
referenced by an object being serialized, saving them too
 Each such object must also implement the Serializable
interface
 Many classes from the Java class library implement
Serializable, including the String class
 The ArrayList class also implements the
Serializable interface, permitting an entire list of
objects to be serialized in one operation
The transient Modifier
 When we serialize an object, sometimes we prefer to
exclude a particular piece of information such as a
password
 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
 For example
private transient int password;
File Choosers
 A GUI-based program sometimes involve the use of
external files
 A file chooser is a specialized dialog box created using
the JFileChooser class
 A file chooser allows the user to browse a disk or other
storage device to select a file
 A text area is similar to a text field, but can contain
multiple lines
 See DisplayFile.java (page 482)
The DisplayFile Program
Color Choosers
 A color chooser is a component that allows a user to
specify a color
 It is similar to a file chooser in that it displays a special
purpose dialog box
 It is created using the JColorChooser class
 A color can be selected using swatches or RGB values
 See DisplayColor.java (page 484)
The DisplayColor Program
Image Icons
 An image icon object represents an image
 ImageIcon objects use either JPEG or GIF images
 They can be used in several situations, such as being
displayed in a label
 A JLabel can contain a String, and ImageIcon, or
both
 The orientation of the label's text and image can be set
explicitly
 See LabelDemo.java (page 487)
 See LabelPanel.java (page 488)
The LabelDemo Program
Key Events
 A key event is generated when a keyboard key is pressed
 Constants in the KeyEvent class can be used to
determine which key was pressed
 The KeyListener interface contains three methods,
representing three events:
• key pressed – a key is pressed
• key released – a key is released
• key typed – called when a pressed key produces a key character
 See Direction.java (page 490)
 See DirectionPanel.java (page 491)
The Direction Program
Animations
 An animation is a series of images that gives the
appearance of movement
 To create the illusion of movement, we use a timer to
change the scene after an appropriate delay
 The Timer class of the javax.swing package
represents a component, even though it has no visual
representation
 A Timer object generates an action event at specified
intervals
Animations
 The start and stop methods of the Timer class start
and stop the timer
 The delay can be set using the Timer constructor or
using the setDelay method
 See Rebound.java (page 496)
 See ReboundPanel.java (page 497)
The Rebound Program
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
key events
animations