Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Eleven: Input/Ouput and Exception Handling.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
CS102--Object Oriented Programming
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
COMP 121 Week 5: Exceptions and Exception Handling.
Chapter 9 Exception Handling. Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference.
Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Catching Exceptions An exception may be thrown by a method when an exceptional occurance happens (and the method does not have the expertise to remedy.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Chapter 11.  Data is often stored in files such as a text file  We need to read that data into our program  Simplest mechanism  Scanner class  First.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 11 – Input/Output and Exception Handling.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Chapter 11  I/O and Exception Handling 1 Chapter 11 I/O and Exception Handling.
Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
Lecture 7 File I/O (and a little bit about exceptions)‏
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Files and Streams CS 21a Chapter 11 of Horstmann.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
Object Oriented Programming
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Input/Output and Exception Handling.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 11 – Input/Output and Exception Handling.
Chapter 16 Streams. Chapter Goals To be able to read and write text files To become familiar with the concepts of text and binary formats To learn about.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Chapter 14 Exception Handling. Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference.
CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Chapter 10 – Input/Output and Exception Handling Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Week 12 – Text Files Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Java Programming Week 9: Input/Ouput and Exception Handling, Files and Streams (Chapter 11 and Chapter 19)
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Input/Output and Exception Handling.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
The Problem Unexpected erroneous situations are often discovered by code which is NOT prepared to remedy the error………. For example.. String in = JOptionPane.showInputDialog(“enter.
Exception Handling.
CSE 501N Fall ’09 17: Exception Handling
Chapter 11 – Input/Output and Exception Handling
Goals To read and write text files To process command line arguments
Chapter 11 – Input/Output and Exception Handling
Exceptions 10-Nov-18.
Chapter Three - Implementing Classes
Chapter 15 – Exception Handling
Advanced Java Programming
Exception Handling.
Chapter 11 Input/Output Exception Handling
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
Exceptions 10-May-19.
Exceptions 5-Jul-19.
Presentation transcript:

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Eleven: Input/Ouput and Exception Handling

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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 learn how to catch exceptions To know when and where to catch an exception Chapter Goals

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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 Reading Text Files

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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(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 Writing Text Files

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. When the input or output file doesn't exist, a FileNotFoundException can occur To handle the exception, label the main method like this: public static void main(String[] args) throws FileNotFoundException FileNotFoundException

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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 */ Mary had a little lamb /* 2 */ Whose fleece was white as snow. /* 3 */ And everywhere that Mary went, /* 4 */ The lamb was sure to go! Program can be used for numbering Java source files A Sample Program

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 01: import java.io.FileReader; 02: import java.io.FileNotFoundException; 03: import java.io.PrintWriter; 04: import java.util.Scanner; 05: 06: public class LineNumberer 07: { 08: public static void main(String[] args) 09: throws FileNotFoundException 10: { 11: Scanner console = new Scanner(System.in); 12: System.out.print("Input file: "); 13: String inputFileName = console.next(); 14: System.out.print("Output file: "); 15: String outputFileName = console.next(); 16: 17: FileReader reader = new FileReader(inputFileName); 18: Scanner in = new Scanner(reader); 19: PrintWriter out = new PrintWriter(outputFileName); 20: int lineNumber = 1; ch11/fileio/LineNumberer.java Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 21: 22: while (in.hasNextLine()) 23: { 24: String line = in.nextLine(); 25: out.println("/* " + lineNumber + " */ " + line); 26: lineNumber++; 27: } 28: 29: out.close(); 30: } 31: } ch11/fileio/LineNumberer.java (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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. Self Check 11.1

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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. Self Check 11.2

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. File Dialog Boxes Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. JFileChooser chooser = new JFileChooser(); FileReader in = null; if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File selectedFile = chooser.getSelectedFile(); reader = new FileReader(selectedFile);... } File Dialog Boxes (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Throw an exception object to signal an exceptional condition Example: IllegalArgumentException: illegal parameter value IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; No need to store exception object in a variable: throw new IllegalArgumentException("Amount exceeds balance"); When an exception is thrown, method terminates immediately Execution continues with an exception handler Throwing Exceptions

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. public class BankAccount { public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; } balance = balance - amount; }... } Example

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Hierarchy of Exception Classes

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. throw exceptionObject; Example: throw new IllegalArgumentException(); Purpose: To throw an exception and transfer control to a handler for this exception type. Syntax 11.1 Throwing an Exception

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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. Self Check 11.3

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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. Self Check 11.4

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Two types of exceptions: Checked oThe compiler checks that you don't ignore them oDue to external circumstances that the programmer cannot prevent oMajority occur when dealing with input and output oFor example, IOException Unchecked: oExtend the class RuntimeException or Error oThey are the programmer's fault oExamples of runtime exceptions: NumberFormatException IllegalArgumentException NullPointerException oExample of error: OutOfMemoryError Checked and Unchecked Exceptions

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Categories aren't perfect: Scanner.nextInt throws unchecked InputMismatchException Programmer cannot prevent users from entering incorrect input This choice makes the class easy to use for beginning programmers 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); But, FileReader constructor can throw a FileNotFoundException Checked and Unchecked Exceptions

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Two choices: 1.Handle the exception 2.Tell compiler that you want method to be terminated when the exception occurs Use throws specifier so method can throw a checked exception public void read(String filename) throws FileNotFoundException { FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader);... } For multiple exceptions: public void read(String filename) throws IOException, ClassNotFoundException Checked and Unchecked Exceptions Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Keep in mind inheritance hierarchy: If method can throw an IOException and FileNotFoundException, only use IOException Better to declare exception than to handle it incompetently Checked and Unchecked Exceptions (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. accessSpecifier returnType methodName(parameterType parameterName,...) throws ExceptionClass, ExceptionClass,... Example: public void read(BufferedReader in) throws IOException Purpose: To indicate the checked exceptions that this method can throw. Syntax 11.2 Exception Specification

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Suppose a method calls the FileReader constructor and the read method of the FileReader class, which can throw an IOException. Which throws specification should you use? Answer: The specification throws IOException is sufficient because FileNotFoundException is a subclass of IOException. Self Check 11.5

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Why is a NullPointerException not a checked exception? Answer: Because programmers should simply check for null pointers instead of trying to handle a NullPointerException. Self Check 11.6

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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 Catching Exceptions Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Example: try { String filename =...; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); String input = in.next(); int value = Integer.parseInt(input);... } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println("Input was not a number"); } Catching Exceptions (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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 Catching Exceptions

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. try { statement statement... } catch (ExceptionClass exceptionObject) { statement statement... } catch (ExceptionClass exceptionObject) { statement statement... }... Syntax 11.3 General Try Block Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Example: try { System.out.println("How old are you?"); int age = in.nextInt(); System.out.println("Next year, you'll be " + (age + 1)); } catch (InputMismatchException exception) { exception.printStackTrace(); } Syntax 11.3 General Try Block (cont.) Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Purpose: To execute one or more statements that may generate exceptions. If an exception occurs and it matches one of the catch clauses, execute the first one that matches. If no exception occurs, or an exception is thrown that doesn't match any catch clause, then skip the catch clauses. Syntax 11.3 General Try Block (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Suppose the file with the given file name exists and has no contents. Trace the flow of execution in the try block in this section. Answer: The FileReader constructor succeeds, and in is constructed. Then the call in.next () throws a NoSuchElementException, and the try block is aborted. None of the catch clauses match, so none are executed. If none of the enclosing method calls catch the exception, the program terminates. Self Check 11.7

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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 code example on page 508. Recall that IOException is a checked exception and NumberFormatException is an unchecked exception. Self Check 11.8

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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" The finally Clause

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. FileReader reader = new FileReader(filename); try { Scanner in = new Scanner(reader); readData(in); } finally { reader.close(); // if an exception occurs, finally clause is also // executed before exception is passed to its handler } The finally Clause

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Executed when try block is exited in any of three ways: After last statement of try block After last statement of catch clause, if this try block caught an exception When an exception was thrown in try block and not caught Recommendation: don't mix catch and finally clauses in same try block The finally Clause

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. try { statement statement... } finally { statement statement... } Syntax 11.4 The finally Clause Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Example: FileReader reader = new FileReader(filename); try { readData(reader); } finally { reader.close(); } Purpose: To ensure that the statements in the finally clause are executed whether or not the statements in the try block throw an exception. Syntax 11.4 The finally Clause (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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 catch clause could not have closed it. Self Check 11.9

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Suppose the file with the given name does not exist. Trace the flow of execution of the code segment in this section. Answer: The FileReader constructor throws an exception. The finally clause is executed. Since reader is null, the call to close is not executed. Next, a catch clause that matches the FileNotFoundException is located. If none exists, the program terminates. Self Check 11.10

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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 Designing Your Own Exception Types

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {} public InsufficientFundsException(String message) { super(message); } } Designing Your Own Exception Types

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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. Self Check 11.11

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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: Exception or IOException are both good choices. Because file corruption is beyond the control of the programmer, this should be a checked exception, so it would be wrong to extend RuntimeException. Self Check 11.12

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Program Asks user for name of file File expected to contain data values First line of file contains total number of values Remaining lines contain the data Typical input file: A Complete Example

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. What can go wrong? File might not exist File might have data in wrong format Who can detect the faults? FileReader constructor will throw an exception when file does not exist Methods that process input need to throw exception if they find error in data format What exceptdions can be thrown? FileNotFoundException can be thrown by FileReader constructor IOException can be thrown by close method of FileReader BadDataException, a custom checked exception class A Complete Example Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Who can remedy the faults that the exceptions report? Only the main method of DataSetTester program interacts with user Catches exceptions Prints appropriate error messages Gives user another chance to enter a correct file A Complete Example (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 01: import java.io.FileNotFoundException; 02: import java.io.IOException; 03: import java.util.Scanner; 04: 05: /** 06: This program reads a file containing numbers and analyzes its contents. 07: If the file doesn't exist or contains strings that are not numbers, an 08: error message is displayed. 09: */ 10: public class DataAnalyzer 11: { 12: public static void main(String[] args) 13: { 14: Scanner in = new Scanner(System.in); 15: DataSetReader reader = new DataSetReader(); 16: 17: boolean done = false; 18: while (!done) 19: { 20: try 21: { 22: System.out.println("Please enter the file name: "); 23: String filename = in.next(); ch11/data/DataAnalyzer.java Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 24: 25: double[] data = reader.readFile(filename); 26: double sum = 0; 27: for (double d : data) sum = sum + d; 28: System.out.println("The sum is " + sum); 29: done = true; 30: } 31: catch (FileNotFoundException exception) 32: { 33: System.out.println("File not found."); 34: } 35: catch (BadDataException exception) 36: { 37: System.out.println("Bad data: " + exception.getMessage()); 38: } 39: catch (IOException exception) 40: { 41: exception.printStackTrace(); 42: } 43: } 44: } 45: } ch11/data/DataAnalyzer.java (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Constructs Scanner object Calls readData method Completely unconcerned with any exceptions If there is a problem with input file, it simply passes the exception to caller The readFile method of the DataSetReader class Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. public double[] readFile(String filename) throws IOException, BadDataException // FileNotFoundException is an IOException { FileReader reader = new FileReader(filename); try { Scanner in = new Scanner(reader); readData(in); } finally { reader.close(); } return data; } The readFile method of the DataSetReader class (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Reads the number of values Constructs an array Calls readValue for each data value private void readData(Scanner in) throws BadDataException { if (!in.hasNextInt()) throw new BadDataException("Length expected"); int numberOfValues = in.nextInt(); data = new double[numberOfValues]; for (int i = 0; i < numberOfValues; i++) readValue(in, i); if (in.hasNext()) throw new BadDataException("End of file expected"); } The readData method of the DataSetReader class Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Checks for two potential errors File might not start with an integer File might have additional data after reading all values Makes no attempt to catch any exceptions The readData method of the DataSetReader class (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. private void readValue(Scanner in, int i) throws BadDataException { if (!in.hasNextDouble()) throw new BadDataException("Data value expected"); data[i] = in.nextDouble(); } The readValue method of the DataSetReader class

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Animation 11.1 –

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 1.DataSetTester.main calls DataSetReader.readFile 2.readFile calls readData 3.readData calls readValue 4.readValue doesn't find expected value and throws BadDataException 5.readValue has no handler for exception and terminates 6.readData has no handler for exception and terminates 7.readFile has no handler for exception and terminates after executing finally clause 8.DataSetTester.main has handler for BadDataException ; handler prints a message, and user is given another chance to enter file name Scenario

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. ch11/data/DataSetReader.java 01: import java.io.FileReader; 02: import java.io.IOException; 03: import java.util.Scanner; 04: 05: /** 06: Reads a data set from a file. The file must have the format 07: numberOfValues 08: value1 09: value2 10:... 11: */ 12: public class DataSetReader 13: { 14: /** 15: Reads a data set. filename the name of the file holding the data the data in the file 18: */ 19: public double[] readFile(String filename) 20: throws IOException, BadDataException 21: { 22: FileReader reader = new FileReader(filename); Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. ch11/data/DataSetReader.java (cont.) 23: try 24: { 25: Scanner in = new Scanner(reader); 26: readData(in); 27: } 28: finally 29: { 30: reader.close(); 31: } 32: return data; 33: } 34: 35: /** 36: Reads all data. in the scanner that scans the data 38: */ 39: private void readData(Scanner in) throws BadDataException 40: { 41: if (!in.hasNextInt()) 42: throw new BadDataException("Length expected"); 43: int numberOfValues = in.nextInt(); 44: data = new double[numberOfValues]; Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. ch11/data/DataSetReader.java (cont.) 45: 46: for (int i = 0; i < numberOfValues; i++) 47: readValue(in, i); 48: 49: if (in.hasNext()) 50: throw new BadDataException("End of file expected"); 51: } 52: 53: /** 54: Reads one data value. in the scanner that scans the data i the position of the value to read 57: */ 58: private void readValue(Scanner in, int i) throws BadDataException 59: { 60: if (!in.hasNextDouble()) 61: throw new BadDataException("Data value expected"); 62: data[i] = in.nextDouble(); 63: } 64: 65: private double[] data; 66: }

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Why doesn't the DataSetReader.readFile method catch any exceptions? Answer: It would not be able to do much with them. The DataSetReader class is a reusable class that may be used for systems with different languages and different user interfaces. Thus, it cannot engage in a dialog with the program user. Self Check 11.13

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Suppose the user specifies a file that exists and is empty. Trace the flow of execution. Answer: DataSetTester.main calls DataSetReader.readFile, which calls readData. The call in.hasNextInt () returns false, and readData throws a BadDataException. The readFile method doesn't catch it, so it propagates back to main, where it is caught. Self Check 11.14