Presentation is loading. Please wait.

Presentation is loading. Please wait.

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,

Similar presentations


Presentation on theme: "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,"— Presentation transcript:

1 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 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 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 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 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 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 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 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 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 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

11 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

12 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

13 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

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

15 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

16 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

17 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

18 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

19 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

20 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

21 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

22 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

23 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

24 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.

25 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)

26 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()));

27 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


Download ppt "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,"

Similar presentations


Ads by Google