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.

Slides:



Advertisements
Similar presentations
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Advertisements

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.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
COMP 121 Week 5: Exceptions and Exception Handling.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
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.
File IO Includes Exceptions. Topics  General concepts  Exception handling  Creating a file in Eclipse  Use of Scanner class  Select a file (LineNumberer)
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.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
Chapter 11  I/O and Exception Handling 1 Chapter 11 I/O and Exception Handling.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
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.
Files and Streams CS 21a Chapter 11 of Horstmann.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Eleven: Input/Ouput and Exception Handling.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Using java’s Scanner class To read from input and from a file. (horstmann ch04 and ch 17)
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Input/Output and Exception Handling.
Two Ways to Store Data in a File Text format Binary format.
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 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
Class Design: Handling Errors Reading: 2 nd Ed: Chapter 15 3 rd Ed: Chapter 11 Exercises 2 nd Ed: P15.5, P15.6 (Hint: look at documentation for Scanner.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Exceptions Handling the unexpected. RHS – SWC 2 The Real World So far, most of our code has been somewhat näive We have assumed that nothing goes wrong…
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
Fall 2006Adapted from Java Concepts Companion Slides1 Files and Streams Advanced Programming ICOM 4015 Lecture 16 Reading: Java Concepts Chapter 16.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
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. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
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.
For Friday Finish reading chapter 9 WebCT quiz 17.
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.
Chapter 12 Exception Handling And Text IO
Introduction Exception handling Exception Handles errors
CSE 501N Fall ’09 17: Exception Handling
Goals To read and write text files To process command line arguments
Chapter 11 – Input/Output and Exception Handling
Some File I/O CS140: Introduction to Computing 1 Savitch Chapter 9.1, 10.1, /25/13.
Exceptions 10-Nov-18.
Chapter 15 – Exception Handling
Working with files.
Advanced Java Programming
Exceptions Handling the unexpected
Exception Handling.
Chapter 11 Input/Output Exception Handling
Chapter 12 Exception Handling and Text IO Part 1
Exception Handling Contents
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
Presentation transcript:

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 construct a FileReader object with the name of the input file.  Then use the FileReader to construct the Scanner

 FileReader reader = new FileReader(“input.txt”);  Scanner in = new Scanner (reader);  Now use standard Scanner objects to read

 Create an output file using PrintWriter  PrintWriter out = new PrintWriter(“output.txt”);  If the output files exits, it is emptied before output  If it doesn’t exist, it will be created  Now use print and println methods to output  out.println(29.95);  out.println(new Rectanble(5,10,15,25);  out.println(“Hello World”);  Converts numbers to decimal string representations  Uses toString to convert objects to strings

 Close input  in.close()  Close output  out.close()  Exist program without close may loose data

 Get a FileNotFoundException  We need the following code public static void main(String[] args) throws FileNotFoundException

import java.io.FileReader; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class LineNumberer { public static void mian(String[] args) throws FileNotFoundException { Scanner console = new Scanner (System.in); System.out.println("Input file: "); String inputFileName = console.next(); System.out.println("Output file: "); String outputFileName = console.next();

FileReader reader = new FileReader(inputFileName); Scanner in = new Scanner(reader); PrintWriter out = new PrintWriter(outputFileName); int lineNumber = 1; while (in.hasNextLine()) { String line = in.nextLine(); out.println("/* " + lineNumber + "*/ " + line); lineNumber ++; } in.close(); out.close(); }

 Windows file name  C:\homework\input.dat  Must use double backslashes in = new FileReader(“c: \\homework\\input.data”);

 Two main aspects to exception handling  Reporting  Recovery  The point of reporting is often far apart from the point of recovery  What do we do if we find a problem?

 Flexible mechanism for passing control from the point of error reporting to a competent recovery handler.  When you encounter an error condition you just throw an appropriate exception.  Then what  Look for an appropriate exception class  Java provides many classes

public class BankAccount { public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; } balance = balance = amount: ………… }

 Instead of IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception;  Can use throw new IllegalArgumentException (“Amount exceeds balance”);

 Checked exceptions  When you call a method that throws a checked exception, compiler checks that you don’t ignore it.  You must tell the compiler what to do  Likely to occur at times – no matter how careful you are  Unchecked Exceptions  Not required to handle  Considered your fault

 Signals the caller that your method may encounter an exception.  Your method may throw multiple exceptions  Separate by commas  Be aware of the hierarchy of the exceptions.

 Try Block  One or more statements that may cause an exception.  Put statements that may cause an exception inside the try block. try { String filename =...; FileReader reader = new FileReader(filename); Scanner in = new scanner(reader); String input = in.next(); int value = Integer.pareseInt(input); }

 Put the handler (what you want done) inside the catch. catch(IOExceptions exception) { exception.printStackTrace(); } catch (NumberFromatException exception) { System.out.println(“Input was not a number”) }

 You need to take some action whether or not an exception is thrown.  For example close your files.  These go in a finally block finally { out.close(); }

 Once a try block is entered, the statements in a finally clause are guaranteed to be executed, whether or not an exception is thrown.

 You have a condition that is not handled by the standard java exceptions.  For example, amount > balance Throw new InsufficitentFundsException(“withdrawal of “ + amount + “ exceeds balance of “ + balance); You need to define the InsufficientFundsException class

 Checked or Unchecked  Fault of external event – checked  Fault of internal event - unchecked

public class InsufficientFundsException extends RuntimeException { public InsufficientFundsExcetpion() { } public InsufficientFundsException(String message) { super(message) }