Transcript Document

Input/Ouput and Exception
Handling
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
2
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
3
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
4
Exception Handling
public class Zero
{
// Deliberately divides by zero to produce an exception.
public static void main (String[] args)
{
int numerator = 10;
int denominator = 0;
System.out.println (numerator / denominator);
System.out.println ("This text will not be printed.");
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Zero.main(Zero.java:8)
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
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
 See ExceptionScope.java
8
Exception Handling
>java Propagation
Program beginning.
Level 1 beginning.
Level 2 beginning.
Level 3 beginning.
The exception message is: / by zero
The call stack trace:
java.lang.ArithmeticException: / by zero
at ExceptionScope.level3(ExceptionScope.java:54)
at ExceptionScope.level2(ExceptionScope.java:41)
at ExceptionScope.level1(ExceptionScope.java:18)
at Propagation.main(Propagation.java:17)
Level 1 ending.
Program ending.
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
 When an exception is thrown, method terminates
immediately
• Execution continues with an exception handler
10
Example
public class BankAccount
{
public void withdraw(double amount)
{
if (amount > balance)
{
IllegalArgumentException exception
= new IllegalArgumentException("Amount
exceeds balance");
throw exception;
}
balance = balance - amount;
}
. . .
}
Hierarchy of Exception Classes
Checked Exceptions
 Two types of exceptions:
• Checked
o The compiler checks that you don't ignore them
o Due to external circumstances that the programmer cannot prevent
o Majority occur when dealing with input and output
o For example, IOException
• Unchecked:
o Extend the class RuntimeException or Error
o They are the programmer's fault
o Examples of runtime exceptions:
NumberFormatException
IllegalArgumentException
NullPointerException
o Example of error:
OutOfMemoryError
13
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
14
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 do 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
Writing Text Files
 To write to a file, construct a PrintWriter object
PrintWriter out = new PrintWriter("output.txt");
 If file already exists, it is emptied before the new data are written into
it
 If file doesn't exist, an empty file is created
 Use print and println to write into a PrintWriter:
out.println(29.95);
out.println("Hello, World!");
 You must close a file when you are done processing it:
out.close();
Otherwise, not all of the output may be written to the disk file
 When the input or output file doesn't exist, a
FileNotFoundException can occur
Reading 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
 See InventoryItem.java
Reading Text Files
 Simplest way to read text: use Scanner class
 To read from a disk file, construct a FileReader
 Then, use the FileReader to construct a Scanner
object
FileReader reader = new
FileReader("input.txt");
Scanner in = new Scanner(reader);
 Use the Scanner methods to read data from file
next, nextLine, nextInt, and nextDouble
A Sample Program
 Reads all lines of a file and sends them to the output file,
preceded by line numbers
 Sample input file:
Mary had a little lamb
Whose fleece was white as snow.
And everywhere that Mary went,
The lamb was sure to go!
 Program produces the output file:
/*
/*
/*
/*
1
2
3
4
*/
*/
*/
*/
Mary had a little lamb
Whose fleece was white as snow.
And everywhere that Mary went,
The lamb was sure to go!
 Program can be used for numbering Java source files
fileio/LineNumberer.java
01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
import
import
import
import
java.io.FileReader;
java.io.FileNotFoundException;
java.io.PrintWriter;
java.util.Scanner;
public class LineNumberer
{
public static void main(String[] args)
throws FileNotFoundException
{
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
System.out.print("Output file: ");
String outputFileName = console.next();
FileReader reader = new FileReader(inputFileName);
Scanner in = new Scanner(reader);
PrintWriter out = new PrintWriter(outputFileName);
int lineNumber = 1;
fileio/LineNumberer.java (cont.)
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31: }
while (in.hasNextLine())
{
String line = in.nextLine();
out.println("/* " + lineNumber + " */ " + line);
lineNumber++;
}
out.close();
}
File Dialog Boxes
Continued
File Dialog Boxes (cont.)
 JFileChooser chooser = new JFileChooser();
FileReader in = null;
if (chooser.showOpenDialog(null) ==
JFileChooser.APPROVE_OPTION)
{
File selectedFile =
chooser.getSelectedFile();
reader = new FileReader(selectedFile);
. . .
}