CSCI213 Spring2013 Lectures IO and Exception Handling
CSCI213 Spring2013 Lectures IO and Exception Handling
Chapter Goals To be able to read and write text files To learn how to throw exceptions To be able to design your own exception classes To understand the difference between checked and unchecked exceptions To know when and where to catch an exception
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
2013-04-15
If file already exists, it is emptied before the new data are written into it If file doesnt exist, an empty file is created Use print and println to write into a PrintWriter:
out.println(29.95); out.println(new Rectangle(5, 10, 15, 25)); 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
4
FileNotFoundException When the input or output file doesnt exist, a FileNotFoundException can occur To handle the exception, label the main method like this:
public static void main(String[] args) throws FileNotFoundException
A Sample Program Reads all lines of a file and sends them to the output file, preceded by line numbers Sample input file: CSCI213
CSCI213, FCSE CSCI213, FCSE, UOWD
2013-04-15
ch10/lines/LineNumberer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import import import import /** java.io.File; java.io.FileNotFoundException; java.io.PrintWriter; java.util.Scanner;
This program applies line numbers to a file. */ public class LineNumberer { public static void main(String[] args) throws FileNotFoundException { // Prompt for the input and output file names Scanner console = new Scanner(System.in); System.out.print("Input file: "); String inputFileName = console.next(); System.out.print("Output file: "); String outputFileName = console.next();
Continued
7
ch10/fileio/LineNumberer.java (cont.)
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 // Construct the Scanner and PrintWriter objects for reading and writing File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter(outputFileName); int lineNumber = 1; // Read the input and write the output while (in.hasNextLine()) { String line = in.nextLine(); out.println("/* " + lineNumber + " */ " + line); lineNumber++; } in.close(); out.close(); } }
Self Check 10.1 What happens when you supply the same name for the input and output files to the LineNumberer program? Answer: When the PrintWriter object is created, the output file is emptied. Sadly, that is the same file as the input file. The input file is now empty and the while loop exits immediately.
2013-04-15
Self Check 10.2 What happens when you supply the name of a nonexistent input file to the LineNumberer program? Answer: The program catches a FileNotFoundException, prints an error message, and terminates.
10
11
12
2013-04-15
Throwing Exceptions Throw an exception object to signal an exceptional condition Example: IllegalArgumentException: Illegal parameter value:
IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception;
Example
public class BankAccount { public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; } balance = balance - amount; } ... }
14
15
2013-04-15
16
Self Check 10.6 How should you modify the deposit method to ensure that the balance is never negative? Answer: Throw an exception if the amount being deposited is less than zero.
17
Self Check 10.7 Suppose you construct a new bank account object with a zero balance and then call withdraw(10). What is the value of balance afterwards? Answer: The balance is still zero because the last statement of the withdraw method was never executed.
18
2013-04-15
The compiler checks that you dont ignore them Due to external circumstances that the programmer cannot prevent Majority occur when dealing with input and output For example, IOException Extend the class RuntimeException or Error They are the programmers fault Examples of runtime exceptions: NumberFormatException IllegalArgumentException NullPointerException
Unchecked
o o o
Deal with checked exceptions principally when programming with files and streams For example, use a Scanner to read a file:
String filename = ...; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader);
20
Continued
21
2013-04-15
22
23
Self Check 10.9 Why is a NullPointerException not a checked exception? Answer: Because programmers should simply check for null pointers instead of trying to handle a NullPointerException.
24
2013-04-15
Catching Exceptions Install an exception handler with try/catch statement try block contains statements that may cause an exception catch clause contains handler for an exception type
Continued
25
26
Catching Exceptions Statements in try block are executed If no exceptions occur, catch clauses are skipped If exception of matching type occurs, execution jumps to catch clause If exception of another type occurs, it is thrown until it is caught by another try block
catch (IOException exception) block
exception contains reference to the exception object that was thrown catch clause can analyze object to find out more details exception.printStackTrace(): Printout of chain of method calls that
lead to exception
27
2013-04-15
28
Self Check 10.11 Is there a difference between catching checked and unchecked exceptions? Answer: No you catch both exception types in the same way, as you can see from the above code example. Recall that IOException is a checked exception and NumberFormatException is an unchecked exception.
29
The finally Clause Exception terminates current method Danger: Can skip over essential code Example:
reader = new FileReader(filename); Scanner in = new Scanner(reader); readData(in); reader.close(); // May never get here
Must execute reader.close() even if exception happens Use finally clause for code that must be executed no matter what
30
10
2013-04-15
31
The finally Clause Executed when try block is exited in any of three ways:
1. After last statement of try block 2. After last statement of catch clause, if this try block caught an exception 3. When an exception was thrown in try block and not caught
32
33
11
2013-04-15
Self Check 10.12 Why was the out variable declared outside the try block? Answer: If it had been declared inside the try block, its scope would only have extended to the end of the try block, and the finally clause could not have closed it.
34
Self Check 10.13 Suppose the file with the given name does not exist. Trace the flow of execution of the code segment in this section. Answer: The PrintWriter constructor throws an exception. The assignment to out and the try block are skipped. The finally clause is not executed. This is the correct behavior because out has not been initialized.
35
Designing Your Own Exception Types You can design your own exception types subclasses of Exception or RuntimeException
if (amount > balance) { throw new InsufficientFundsException( "withdrawal of " + amount + " exceeds balance of " + balance); }
Make it an unchecked exception programmer could have avoided it by calling getBalance first Extend RuntimeException or one of its subclasses Supply two constructors
1. Default constructor 2. A constructor that accepts a message string describing reason for exception
36
12
2013-04-15
37
Self Check 10.14 What is the purpose of the call super(message) in the second InsufficientFundsException constructor? Answer: To pass the exception message string to the RuntimeException superclass.
38
Self Check 10.15 Suppose you read bank account data from a file. Contrary to your expectation, the next input value is not of type double. You decide to implement a BadDataException. Which exception class should you extend? Answer: Because file corruption is beyond the control of the programmer, this should be a checked exception, so it would be wrong to extend RuntimeException or IllegalArgumentException. Because the error is related to input, IOException would be a good choice.
39
13
2013-04-15
40
14