File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ source program destination 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 Standard I/O We use System.out with println statements We use System.in with Scanner System.err also goes to the console, by default standard input System.in program standard output System.out File I/O: Setting up streams from files Input: Scanner Output: PrintWriter standard input System.in input file Scanner program PrintWriter Scanner PrintWriter standard output System.out output file output file standard Error System.err input file Scanner standard Error System.err Dr. Papalaskari 1
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; int value; String filename = "test.txt"; PrintWriter outfile = new PrintWriter(fileName); text output file output streams should be closed explicitly Random rand = new Random(); 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 Output file has been created: test.txt Random rand = new Random(); Output for (int line=1; line <= MAX; line++) for (int num=1; num <= MAX; num++) value = rand.nextint(90) + 10; Sample test.txt File outfile.print(value + " "); 77 46 24 67 45 37 32 40 39 10 outfile.println(); 90 91 71 64 82 80 68 18 83 89 25 80 45 75 74 40 15 90 79 59 outfile.close(); 44 43 95 85 93 61 15 20 52 86 System.out.println("Output 60 85 18 73 56 file 41 has been 35 created: 67 21 " + filename); 42 93 25 89 47 13 27 51 94 76 13 33 25 48 42 27 24 88 18 32 17 71 10 90 88 60 19 89 54 21 92 45 26 47 68 55 98 34 38 98 38 48 59 90 12 86 36 11 65 41 62 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) Dr. Papalaskari 2
Errors and Exceptions Errors are unrecoverable situations LinkageError ThreadDeath VirtualMachinError Exceptions can be caught and handled Trying to divide by zero Trying to use an array index that is out of bounds Trying to read from a file that cannot be found An I/O error when trying to read or write Security problem Exception Handling Three ways to deal with exceptions Ignore them Let the java runtime environment deal with them Handle them where they occur Handle them at another place in the program 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); Uncaught Exception 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); where exception occurred call stack trace System.out.println("This text will not be printed."); System.out.println("This text will not be printed."); Dr. Papalaskari 3
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 s following the try statement (skips catch clauses) Zero.java -- updated public class Zero public static void main(string[] args) int numer = 10; int denom = 0; try System.out.println (numer/denom); catch (ArithmeticException problem) System.out.println ( Bad division ); System.out.println ( this will not print ); But is our trace gone??? No Methods exist to get the trace and system error message Method: getmessage() Returns a string explaining the reason the exception was thrown Method: printstacktrace() Prints the call stack trace indicating where the error occured Change the catch catch (ArithmeticException problem) System.out.println("Bad division"); System.out.println("The exception message + problem.getmessage()); System.out.println(); System.out.println("The call stack trace:"); problem.printstacktrace(); Dr. Papalaskari 4
Catch clauses - RunTimeException Each catch handles one particular type of exception 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 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; Scanner scan = new Scanner(System.in); System.out.print("Enter product code (XXX to quit): "); code = scan.nextline(); 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); 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.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); System.out.println("# of valid codes entered: " + valid); System.out.println("# of banned codes entered: " + banned); Dr. Papalaskari 5
finally clause (optional) The Exception Class Hierarchy 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 ); Checked Exceptions An exception is either checked or unchecked A checked exception must either be caught 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 caught or listed in a throws clause Unchecked Exceptions An unchecked exception does not require explicit handling, though it could be processed that way Errors are similar to RuntimeException and its descendants in that: Errors should not be caught Errors do not require a throws clause Dr. Papalaskari 6
Unchecked Exceptions 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 Quick Check Which of these exceptions are checked and which are unchecked? the only ones that are unchecked NullPointerException IndexOutOfBoundsException ClassNotFoundException NoSuchMethodException ArithmeticException Dr. Papalaskari 7
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 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) 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); Dr. Papalaskari 8