Chapter Goals. Chapter Eleven: Input/Ouput and Exception Handling

Similar documents
D06 PROGRAMMING with JAVA

D06 PROGRAMMING with JAVA

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

CS 111 Classes I 1. Software Organization View to this point:

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Introduction to Java

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

AP Computer Science Static Methods, Strings, User Input

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

What are exceptions? Bad things happen occasionally

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Lecture J - Exceptions

Using Files as Input/Output in Java 5.0 Applications

CS506 Web Design and Development Solved Online Quiz No. 01

Course Intro Instructor Intro Java Intro, Continued

Question R11.3. R11.3 How do you open a file whose name contains a backslash, like c:\temp\output.dat?

Carron Shankland. Content. String manipula3on in Java The use of files in Java The use of the command line arguments References:

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Basics of Java Programming Input and the Scanner class

Chapter 2: Elements of Java

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Object-Oriented Programming in Java

13 File Output and Input

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

AP Computer Science File Input with Scanner

Install Java Development Kit (JDK) 1.8

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

Creating a Simple, Multithreaded Chat System with Java

Building Java Programs

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Topic 11 Scanner object, conditional execution

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Java Programming Language

Building Java Programs

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Event-Driven Programming

Software Construction

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

Java Interview Questions and Answers

J a v a Quiz (Unit 3, Test 0 Practice)

Reading Input From A File

JAVA.UTIL.SCANNER CLASS

public static void main(string args[]) { System.out.println( "f(0)=" + f(0));

public static void main(string[] args) { System.out.println("hello, world"); } }

6.1. Example: A Tip Calculator 6-1

Files and input/output streams

Explain the relationship between a class and an object. Which is general and which is specific?

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Software Development in Java

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

WRITING DATA TO A BINARY FILE

Chapter 13 - Inheritance

Simple Java I/O. Streams

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

CS 121 Intro to Programming:Java - Lecture 11 Announcements

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Inheritance, overloading and overriding

Part I. Multiple Choice Questions (2 points each):

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Java from a C perspective. Plan

Sample CSE8A midterm Multiple Choice (circle one)

AP Computer Science Java Mr. Clausen Program 9A, 9B

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Chapter 2 Introduction to Java programming

AP Computer Science Java Subset

Visit us at

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Introduction to Java. CS 3: Computer Programming in Java

No no-argument constructor. No default constructor found

Licensed for viewing only. Printing is prohibited. For hard copies, please purchase from

Copyright. Restricted Rights Legend. Trademarks or Service Marks. Copyright 2003 BEA Systems, Inc. All Rights Reserved.

D06 PROGRAMMING with JAVA

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

LOOPS CHAPTER CHAPTER GOALS

D06 PROGRAMMING with JAVA

CS193j, Stanford Handout #10 OOP 3

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Dennis Olsson. Tuesday 31 July

Classes Dennis Olsson

Building a Multi-Threaded Web Server

Chapter 3. Input and output. 3.1 The System class

Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006. Final Examination. January 24 th, 2006

Using Two-Dimensional Arrays

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

CS 106 Introduction to Computer Science I

JAVA ARRAY EXAMPLE PDF

Arrays. Introduction. Chapter 7

Lab Experience 17. Programming Language Translation

ICOM 4015: Advanced Programming

Line-based file processing

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

D06 PROGRAMMING with JAVA

Continuous Integration Part 2

Transcription:

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 learn how to catch exceptions To know when and where to catch an exception Chapter Eleven: Input/Ouput and Exception Handling 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"); Use the Scanner methods to read data from file next, nextline, nextint, and nextdouble 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(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 FileNotFoundException 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 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 */ 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 1

ch11/fileio/linenumberer.java 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: 19: PrintWriter out = new PrintWriter(outputFileName); 20: int linenumber = 1; ch11/fileio/linenumberer.java (cont.) 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: Self Check 11.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. Self Check 11.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. File Dialog Boxes 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); 2

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; 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 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 Syntax 11.1 Throwing an Exception throw exceptionobject; Example: throw new IllegalArgumentException(); Purpose: To throw an exception and transfer control to a handler for this exception type. Self Check 11.3 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.4 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 of the withdraw method was never executed. 3

Checked and Unchecked 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 Checked and Unchecked Exceptions 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 = ; But, FileReader constructor can throw a FileNotFoundException Checked and Unchecked Exceptions 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 Checked and Unchecked Exceptions (cont.) 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 public void read(string filename) throws FileNotFoundException For multiple exceptions: public void read(string filename) throws IOException, ClassNotFoundException Syntax 11.2 Exception Specification accessspecifier returntype methodname(parametertype parametername, ) throws ExceptionClass, ExceptionClass, Example: public void read(bufferedreader in) throws IOException Self Check 11.5 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. Purpose: To indicate the checked exceptions that this method can throw. 4

Self Check 11.6 Why is a NullPointerException not a checked exception? Answer: Because programmers should simply check for null pointers instead of ing to handle a NullPointerException. Catching Exceptions Install an exception handler with /catch block contains s that may cause an exception catch clause contains handler for an exception type Catching Exceptions (cont.) Example: String filename = ; 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 Statements in 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 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 Syntax 11.3 General Try Block catch (ExceptionClass exceptionobject) catch (ExceptionClass exceptionobject) Syntax 11.3 General Try Block (cont.) Example: 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(); 5

Syntax 11.3 General Try Block (cont.) Purpose: To execute one or more s 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. Self Check 11.7 Suppose the file with the given file name exists and has no contents. Trace the flow of execution in the block in this section. Answer: The FileReader constructor succeeds, and in is constructed. Then the call in.next() throws a NoSuchElementException, and the 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.8 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. The finally Clause Exception terminates current method Danger: Can skip over essential code Example: reader = new FileReader(filename); 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 readdata(in); finally reader.close(); // if an exception occurs, finally clause is also // executed before exception is passed to its handler The finally Clause Executed when block is exited in any of three ways: After last of block After last of catch clause, if this block caught an exception When an exception was thrown in block and not caught Recommendation: don't mix catch and finally clauses in same block 6

Syntax 11.4 The finally Clause finally Syntax 11.4 The finally Clause (cont.) Example: readdata(reader); finally reader.close(); Purpose: To ensure that the s in the finally clause are executed whether or not the s in the block throw an exception. Self Check 11.9 Why was the out variable declared outside the block? Answer: If it had been declared inside the block, its scope would only have extended to the end of the block, and the catch clause could not have closed it. Self Check 11.10 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. 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 Designing Your Own Exception Types public class InsufficientFundsException extends RuntimeException public InsufficientFundsException() public InsufficientFundsException(String message) super(message); 7

Self Check 11.11 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.12 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. A Complete Example 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: 3 1.45-2.1 0.05 A Complete Example 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 (cont.) 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 ch11/data/dataanalyzer.java 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: 21: 22: System.out.println("Please enter the file name: "); 23: String filename = in.next(); 8

ch11/data/dataanalyzer.java (cont.) 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: The readfile method of the DataSetReader class 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 (cont.) public double[] readfile(string filename) throws IOException, BadDataException // FileNotFoundException is an IOException readdata(in); finally reader.close(); return data; The readdata method of the DataSetReader class 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 (cont.) 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 readvalue method of the DataSetReader class private void readvalue(scanner in, int i) throws BadDataException if (!in.hasnextdouble()) throw new BadDataException("Data value expected"); data[i] = in.nextdouble(); 9

Animation 11.1 Scenario 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 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. 16: @param filename the name of the file holding the data 17: @return the data in the file 18: */ 19: public double[] readfile(string filename) 20: throws IOException, BadDataException 21: 22: ch11/data/datasetreader.java (cont.) 23: 24: 25: 26: readdata(in); 27: 28: finally 29: 30: reader.close(); 31: 32: return data; 33: 34: 35: /** 36: Reads all data. 37: @param 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]; 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. 55: @param in the scanner that scans the data 56: @param 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: Self Check 11.13 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. 10

Self Check 11.14 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. 11