Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.

Slides:



Advertisements
Similar presentations
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Advertisements

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.
COMP 121 Week 5: Exceptions and Exception Handling.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
1 Chapter 10: Exceptions and I/O Streams Original Slides by John Lewis and William Loftus Modified significantly by Bob Roggio.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
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.
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.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
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.
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.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Eleven: Input/Ouput and Exception Handling.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting.
Java Software Solutions Foundations of Program Design Sixth Edition
Preventing and Correcting Errors
1 Advanced Flow of Control - Introduction - zTwo additional mechanisms for controlling process execution are exceptions and threads zChapter 14 focuses.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 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.
10-1 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.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Java Software Solutions Lewis and Loftus Chapter 14 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Advanced Flow of Control --
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Exceptions Chapter 10 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
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.
CSE 501N Fall ‘09 18: Files and Streams 06 November 2009 Nick Leidenfrost.
© 2004 Pearson Addison-Wesley. All rights reserved April 24, 2006 Exceptions (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING 2006.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
1 Chapter 10: Exceptions and I/O Streams Original Slides by John Lewis and William Loftus Modified significantly by Bob Roggio, July 2007.
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)
Chapter 10 Exceptions 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
© 2004 Pearson Addison-Wesley. All rights reserved December 5, 2007 I/O Exceptions & Working with Files ComS 207: Programming I (in Java) Iowa State University,
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
CSE 1201 Object Oriented Programming
Streams & File Input/Output (I/O)
10 Exceptions Software Solutions Lewis & Loftus java 5TH EDITION
04/14/14 Exceptions.
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
CSS 161: Fundamentals of Computing
Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.
Abdulmotaleb El Saddik University of Ottawa
Exception Handling.
Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Exceptions (part 2) December 3, 2007 ComS 207: Programming I (in Java)
I/O Exceptions & Working with Files
Chapter 11 Exceptions Java Software Solutions
Presentation transcript:

Input/Ouput and Exception Handling

2 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

3 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

4 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 Zero.java

5 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)

6 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 ProductCodes.java

7 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

8 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 Propagation.java  See ExceptionScope.java ExceptionScope.java

9 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.

10 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

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

Hierarchy of Exception Classes

13 Checked Exceptions  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

14 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

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 Character Streams Byte Streams Data Streams Processing Streams Input Streams Output 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 CheckInventory.java  See InventoryItem.java 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 */ 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

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: Scanner in = new Scanner(reader); 19: PrintWriter out = new PrintWriter(outputFileName); 20: int lineNumber = 1;

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: }

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);... }