File I/O and Exceptions

Similar documents
I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Introduction to Software Design

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP File Access 1

I/O Streams. COMP 202 File Access. Standard I/O. I/O Stream Categories

Chapter 11 Exceptions

Exceptions (part 2) An exception is an object that describes an unusual or erroneous situation. Quick Review of Last Lecture.

CSC 1051 Data Structures and Algorithms I

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

BBM 102 Introduction to Programming II Spring Exceptions

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name: Question Value Score

ECE 122. Engineering Problem Solving with Java

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

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

Selection Statements and operators

Happy Cinco de Mayo!!!!

CSC 1051 Data Structures and Algorithms I

BBM 102 Introduction to Programming II Spring 2017

Lecture 19 Programming Exceptions CSE11 Fall 2013

More on Exception Handling

Happy Cinco de Mayo!!!!

CSC 1214: Object-Oriented Programming

Name: Checked: Preparation: Write the output of DeckOfCards.java to a text file Submit through Blackboard by 8:00am the morning of Lab.

More on Exception Handling

CSC 1051 Data Structures and Algorithms I

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Selection and Repetition Revisited

Selection Statements and operators

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Exceptions. Outline 7/31/2012. Exceptions. Exception handling is an important aspect of objectoriented. Chapter 10 focuses on:

Exceptions - Example. Exceptions - Example

Name: Checked: Preparation: Investment Calculator with input and output to text files Submit through Blackboard by 8:00am the morning of Lab.

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Selection and Repetition

Programming II (CS300)

Exceptions. COMP 202 Exceptions. Exceptions. Exceptions. An exception is an object that describes an unusual or erroneous situation

Java Errors and Exceptions. Because Murphy s Law never fails

National University. Faculty of Computer Since and Technology Object Oriented Programming

Using Classes and Objects

C16b: Exception Handling

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

Chapter 12 Exception Handling

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

Programming II (CS300)

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name

Algorithms and Conditionals

Introduction to Arrays

Iterators and File Input

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Java I/O and Control Structures

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Introduction to Computer Science II CS S-22 Exceptions

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Java I/O and Control Structures Algorithms in everyday life

Software Practice 1 - Error Handling

Here is a hierarchy of classes to deal with Input and Output streams.

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP 202 File Access 1

Input-Output and Exception Handling

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

Improved algorithm. Java code. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm

Java code. Updated program. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm. Improved algorithm

Selection and Repetition Revisited

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Introduction Unit 4: Input, output and exceptions

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

What are Exceptions?

Sri Vidya College of Engineering & Technology Question Bank

Object Oriented Programming Exception Handling

Control flow, conditionals, boolean expressions, block statements, nested statements. Course website:

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

Chapter 13 Exception Handling

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015

C17: File I/O and Exception Handling

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name: KEY. Question Value Score

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Data Structures. 02 Exception Handling

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Text User Interfaces. Keyboard IO plus

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

File I/O Array Basics For-each loop

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

2: Basics of Java Programming

Full file at Chapter 2 - Inheritance and Exception Handling

Recitation 3. 2D Arrays, Exceptions

EXCEPTION HANDLING. Summer 2018

Object Oriented Programming

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Transcription:

File I/O and Exceptions CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this presentation are adapted from Barbara Zimmerman s CSC 1051 slides and from the slides accompanying Java Software Solutions by Lewis & Loftus

I/O Streams Programs read information from input streams and write information to output streams source program destination

Standard I/O We use System.in with Scanner We use System.out with println statements System.err also goes to the console, by default standard input System.in program standard output System.out standard Error System.err

File I/O: Setting up streams from files Input: Scanner Output: PrintWriter standard input System.in Scanner program PrintWriter standard output System.out output file input file Scanner PrintWriter output file input file Scanner standard Error System.err

//******************************************************************** // TestData.java Author: Lewis/Loftus // // Demonstrates I/O exceptions and the use of a character file // output stream. //******************************************************************** import java.util.random; import java.io.*; public class TestData // Creates a file of test data that consists of ten lines each // containing ten integer values in the range 10 to 99. public static void main(string[] args) throws IOException final int MAX = 10; continue int value; String filename = "test.txt"; PrintWriter outfile = new PrintWriter(fileName); text output file

continue Random rand = new Random(); output streams should be closed explicitly for (int line=1; line <= MAX; line++) for (int num=1; num <= MAX; num++) value = rand.nextint(90) + 10; outfile.print(value + " "); outfile.println(); use just like System.out outfile.close(); System.out.println("Output file has been created: " + filename); System.out can still be used for other messages

Sample test.txt File created output streams should be closed explicitly 77 46 24 67 45 37 32 40 39 10 continue 90 91 71 64 82 80 68 18 83 89 25 80 45 75 74 40 15 90 79 59 Random rand = new Random(); 44 43 95 85 93 61 15 20 52 86 for (int line=1; 60 line 85 <= MAX; 18 line++) 73 56 41 35 67 21 42 93 25 89 47 13 27 51 94 76 13 for (int num=1; 33 num 25 <= MAX; 48 num++) 42 27 24 88 18 32 17 71 10 90 88 60 19 89 54 21 92 value = rand.nextint(90) 45 26 47 + 10; 68 55 98 34 38 98 38 outfile.print(value 48 59 + 90 " "); 12 86 36 11 65 41 62 outfile.println(); use just like System.out outfile.close(); System.out.println("Output file has been created: " + filename); Output System.out can still be used for other messages Output file has been created: test.txt

The IOException Class Operations performed by some I/O classes may throw an IOException A file 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 all methods that do file I/O must list this exception: throws IOException unless they contain code to handle it (more on this later)

Exception Handling Three ways to deal an exception: Ignore Let the java runtime environment deal with it the program will terminate and produce an appropriate message Handle it where it occurs use try/catch block Handle it at another place in the program use try/catch block elsewhere The Java API has a predefined set of exceptions that can occur during execution

Uncaught Exception //******************************************************************** // Zero.java Author: Lewis/Loftus // // Demonstrates an uncaught exception. //******************************************************************** 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.");

Uncaught Exception where exception occurred Output (when program terminates) //******************************************************************** // Zero.java Author: Lewis/Loftus Exception // in thread "main" java.lang.arithmeticexception: / by zero // Demonstrates Zero.main(Zero.java:17) an uncaught exception. //******************************************************************** 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); call stack trace System.out.println("This text will not be printed.");

try / catch Create a try block surrounding code that we think may cause an exception catch clause has code to tell it what to do the exception handler Can have multiple catch clauses One for each type of exception thrown by try block If no exception is thrown, processing continues following the try statement (skips catch clauses)

Zero.java -- updated public class Zero public static void main(string[] args) int numerator = 10; int denominator = 0; try System.out.println (numerator/denominator); catch (ArithmeticException problem) System.out.println ( Bad division ); System.out.println ( this will not print );

catch clauses handle particular types of exceptions. Examples: StringIndexOutOfBoundsException Thrown by a charat method Thrown by a substring method NumberformatException Thrown by a parseint method If the string does not contain an integer ArithmeticException Thrown by division by zero IndexOutOfBoundsException bad index in array

//******************************************************************** // ProductCodes.java Author: Lewis/Loftus // // Demonstrates the use of a try-catch block. //******************************************************************** import java.util.scanner; public class ProductCodes // Counts the number of product codes that are entered with a // zone of R and and district greater than 2000. public static void main(string[] args) String code; char zone; int district, valid = 0, banned = 0; continue Scanner scan = new Scanner(System.in); System.out.print("Enter product code (XXX to quit): "); code = scan.nextline();

continue while (!code.equals("xxx")) try zone = code.charat(9); district = Integer.parseInt(code.substring(3, 7)); valid++; if (zone == 'R' && district > 2000) banned++; catch (StringIndexOutOfBoundsException exception) System.out.println("Improper code length: " + code); catch (NumberFormatException exception) System.out.println("District is not numeric: " + code); System.out.print("Enter product code (XXX to quit): "); code = scan.nextline(); System.out.println("# of valid codes entered: " + valid); System.out.println("# of banned codes entered: " + banned);

continue Sample Run while Enter (!code.equals product code ("XXX")) (XXX to quit): TRV2475A5R-14 Enter product code (XXX to quit): TRD1704A7R-12 try Enter product code (XXX to quit): TRL2k74A5R-11 District zone = code.charat(9); is not numeric: TRL2k74A5R-11 Enter district product = Integer.parseInt(code.substring(3, (XXX to quit): TRQ2949A6M-04 7)); Enter valid++; product code (XXX to quit): TRV2105A2 Improper if (zone code == 'R' length: && district TRV2105A2 > 2000) Enter banned++; product code (XXX to quit): TRQ2778A7R-19 Enter product code (XXX to quit): XXX catch (StringIndexOutOfBoundsException exception) # of valid codes entered: 4 # of System.out.println banned codes entered: ("Improper 2 code length: " + code); catch (NumberFormatException exception) System.out.println("District is not numeric: " + code); System.out.print ("Enter product code (XXX to quit): "); code = scan.nextline(); System.out.println("# of valid codes entered: " + valid); System.out.println("# of banned codes entered: " + banned);

finally clause (optional) Executes no matter how the try block is exited Executes if an exception has been thrown Executes if an exception has not been thrown Must be after all the catch clauses finally System.out.println( Finally clause );

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

//******************************************************************** // Propagation.java Author: Lewis/Loftus // // Demonstrates exception propagation. //******************************************************************** public class Propagation // Invokes the level1 method to begin the exception demonstration. static public void main(string[] args) ExceptionScope demo = new ExceptionScope(); System.out.println("Program beginning."); demo.level1(); System.out.println("Program ending.");

Output //******************************************************************** // Program Propagation.java beginning. Author: Lewis/Loftus // Level 1 beginning. // Level Demonstrates 2 beginning. exception propagation. //******************************************************************** Level 3 beginning. public class Propagation The exception message is: / by zero // The Invokes call stack the level1 trace: method to begin the exception demonstration. java.lang.arithmeticexception: / by zero static public at ExceptionScope.level3(ExceptionScope.java:54) void main (String[] args) at ExceptionScope.level2(ExceptionScope.java:41) ExceptionScope demo = new ExceptionScope(); at ExceptionScope.level1(ExceptionScope.java:18) System.out.println("Program at Propagation.main(Propagation.java:17) beginning."); demo.level1(); Level System.out.println("Program 1 ending. ending."); Program ending.

//******************************************************************** // ExceptionScope.java Author: Lewis/Loftus // // Demonstrates exception propagation. //******************************************************************** public class ExceptionScope // Catches and handles the exception that is thrown in level3. public void level1() System.out.println("Level 1 beginning."); continue try level2(); catch (ArithmeticException problem) System.out.println(); System.out.println("The exception message is: " + problem.getmessage()); System.out.println();

continue System.out.println("The call stack trace:"); problem.printstacktrace(); System.out.println(); System.out.println("Level 1 ending."); // Serves as an intermediate level. The exception propagates // through this method back to level1. public void level2() System.out.println("Level 2 beginning."); level3(); System.out.println("Level 2 ending."); continue

continue // Performs a calculation to produce an exception. It is not // caught and handled at this level. public void level3() int numerator = 10, denominator = 0; System.out.println("Level 3 beginning."); int result = numerator / denominator; System.out.println("Level 3 ending.");

Checked vs. Unchecked Exceptions Checked exceptions: Java requires that certain exceptions (e.g., IOException) are handled in some way. They can be either caught or listed in the throws clause of any method that may throw or propagate them Unchecked exceptions and Errors: Can be either caught or ignored Generally, Errors should NOT be caught

Unchecked Exceptions Checked exceptions Two options: 1) catch and handle - OR - 2) list in throws clause of any method that may throw or propagate it

Another view which are unchecked? Image source: https://thenewcircle.com/static/bookshelf/java_fundamentals_tutorial/images/exceptionclasshierarchy.png

Exception class there is much, much more the only ones that are unchecked

Which are Checked? NullPointerException IndexOutOfBoundsException StackOverflowError NullPointerException FileNotFoundException OutOfMemoryError NoSuchMethodException ThreadDeath ArithmeticException ClassNotFoundException

The throw Statement Exceptions are thrown using the throw statement Usually a throw statement is executed inside an if statement that evaluates a condition to see if the exception should be thrown See CreatingExceptions.java See OutOfRangeException.java

//******************************************************************** // CreatingExceptions.java Author: Lewis/Loftus // // Demonstrates the ability to define an exception via inheritance. //******************************************************************** import java.util.scanner; public class CreatingExceptions // Creates an exception object and possibly throws it. public static void main(string[] args) throws OutOfRangeException final int MIN = 25, MAX = 40; Scanner scan = new Scanner(System.in); OutOfRangeException problem = new OutOfRangeException("Input value is out of range."); System.out.print("Enter an integer value between " + MIN + " and " + MAX + ", inclusive: "); int value = scan.nextint(); // Determine if the exception should be thrown if (value < MIN value > MAX) throw problem; System.out.println("End of main method."); // may never reach

//******************************************************************** // OutOfRangeException.java Author: Lewis/Loftus // // Represents an exceptional condition in which a value is out of // some particular range. //******************************************************************** public class OutOfRangeException extends Exception // Sets up the exception object with a particular message. OutOfRangeException(String message) super(message); Sample Run Enter an integer value between 25 and 40, inclusive: 69 Exception in thread "main" OutOfRangeException: Input value is out of range. at CreatingExceptions.main(CreatingExceptions.java:20)