chapter 8: exceptions and i/o streams presentation slides for java software solutions foundations of...

40
Chapter 8: Exceptions and I/O Chapter 8: Exceptions and I/O Streams 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.

Post on 20-Dec-2015

228 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

Chapter 8: Exceptions and I/O Chapter 8: Exceptions and I/O Streams Streams

Presentation slides for

Java Software SolutionsFoundations 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.

Page 2: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

2

Exceptions and I/O StreamsExceptions 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

Page 3: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

3

ExceptionsExceptions

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

Page 4: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

4

Exception HandlingException 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

Page 5: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

5

Exception HandlingException 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)

Page 6: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

6

The try StatementThe 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)

Page 7: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

7

The finally ClauseThe 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

Page 8: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

8

Exception PropagationException 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)

Page 9: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

9

The throw StatementThe 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)

Page 10: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

10

Checked ExceptionsChecked 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

Page 11: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

Unchecked ExceptionsUnchecked 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

Page 12: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

I/O StreamsI/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

Page 13: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

I/O StreamsI/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

Page 14: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

I/O StreamsI/O Streams

CharacterStreams

ByteStreams

DataStreams

ProcessingStreams

Input Streams

Output Streams

Page 15: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

Character vs. Byte StreamsCharacter 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

Page 16: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

Data vs. Processing StreamsData 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

Page 17: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

The IOException ClassThe 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

Page 18: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

Standard I/OStandard 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

Page 19: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

Standard I/OStandard I/O

PrintStream objects automatically have print and println methods defined for them

The PrintWriter class is needed for advanced internationalization and error checking

Page 20: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

The Keyboard ClassThe 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

Page 21: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

The Keyboard ClassThe 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

Page 22: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

The Keyboard ClassThe 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

Page 23: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

Text FilesText 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)

Page 24: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

Text FilesText 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

Page 25: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

Object SerializationObject 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

Page 26: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

Object SerializationObject 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)

Page 27: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

Object SerializationObject 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

Page 28: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

The transient ModifierThe 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;

Page 29: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

File ChoosersFile 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)

Page 30: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

The DisplayFile ProgramThe DisplayFile Program

Page 31: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

Color ChoosersColor 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)

Page 32: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

The DisplayColor ProgramThe DisplayColor Program

Page 33: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

Image IconsImage 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)

Page 34: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

The LabelDemo ProgramThe LabelDemo Program

Page 35: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

Key EventsKey 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)

Page 36: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

The Direction ProgramThe Direction Program

Page 37: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

AnimationsAnimations

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

Page 38: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

AnimationsAnimations

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)

Page 39: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

The Rebound ProgramThe Rebound Program

Page 40: Chapter 8: Exceptions and I/O Streams Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William

SummarySummary

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