Input/Output and Exception Handling Copyright © 2014 by John Wiley & Sons. All rights reserved. 1 Goals To To To To read and write text files process command line arguments throw and catch exceptions implement programs that propagate checked exceptions Copyright © 2014 by John Wiley & Sons. All rights reserved. 2 Read Text Files Read Text Files: • Use Scanner class for reading text files • To read from a disk file: 1. Construct a File object representing the input file File inputFile = new File("input.txt"); 2. Use this File object to construct a Scanner object: Scanner in = new Scanner(reader); 3. Use the Scanner methods to read data from file next(), nextInt(), and nextDouble() Copyright © 2014 by John Wiley & Sons. All rights reserved. 3 Read Text Files Process the text in file: • A loop to process numbers in the input file: while (in.hasNextDouble()){ double value = in.nextDouble(); //Process value. } Copyright © 2014 by John Wiley & Sons. All rights reserved. 4 Write to a file Write to a file: 1. 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. 2. Use print and println to write into a PrintWriter: out.println("Hello, World!"); out.printf("Total: %8.2f\n", total); Copyright © 2014 by John Wiley & Sons. All rights reserved. 5 Write to a file 3. You must close a file when you are done processing it: in.close(); out.close(); Otherwise, not all of the output may be written to the disk file. Copyright © 2014 by John Wiley & Sons. All rights reserved. 6 FileNotFoundException When the input or output file doesn't exist, a FileNotFoundException can occur. Copyright © 2014 by John Wiley & Sons. All rights reserved. 7 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 { PrintWriter out = new PrintWriter("output.txt"); … } Copyright © 2014 by John Wiley & Sons. All rights reserved. 8 Programming Question Read a file input.txt containing numbers input.txt 32 54 67.5 29 35 80 115 44.5 100 65 Write the numbers in a column followed by their total in a file output.txt: Total: 32.00 54.00 67.50 29.00 35.00 80.00 115.00 44.50 100.00 65.00 622.00 Program template in next slide • Hint: use printf statements to write to file. Copyright © 2014 by John Wiley & Sons. All rights reserved. 9 public class Total { public static void main(String[] args) throws FileNotFoundException { //TODO: Construct the Scanner object to read from input.txt file //TODO: Construct the PrintWriter object for writing in file output.txt //TODO: Read the input and write the output //TODO: Close reader and writer } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 10 Answer import import import import Total.java java.io.File; java.io.FileNotFoundException; java.io.PrintWriter; java.util.Scanner; public class Total { public static void main(String[] args) throws FileNotFoundException { // Construct the Scanner object to read from input.txt file File inputFile = new File("input.txt"); Scanner in = new Scanner(inputFile); // Construct the PrintWriter object for writing in file output.txt PrintWriter out = new PrintWriter("output.txt"); // Read the input and write the output double total = 0; while (in.hasNextDouble()) { double value = in.nextDouble(); out.printf("%15.2f\n", value); total = total + value; } out.printf("Total: %8.2f\n", total); //close reader and writer in.close(); out.close(); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 11 Question What happens when you supply the name of a nonexistent input file to the Total program? Try it out if you are not sure. Copyright © 2014 by John Wiley & Sons. All rights reserved. 12 Answer Answer: The program throws a FileNotFoundException and terminates. Copyright © 2014 by John Wiley & Sons. All rights reserved. 13 Question What exception do you get when input is not a properly formatted number when calling parseInt() method? String population = line.substring(i); int populationVal = Integer.parseInt(population); • Look up in Java API • Try some code with improperly formatted numbers Copyright © 2014 by John Wiley & Sons. All rights reserved. 14 Answer If the input is not a properly formatted number when calling parseInt or parseDouble method NumberFormatException occurs Copyright © 2014 by John Wiley & Sons. All rights reserved. 15 NumberFormatException Copyright © 2014 by John Wiley & Sons. All rights reserved. 16 Programming Question To see a NumberFormatException , try the following code: public class ExceptionDemo { public static void main(String args[]) { String strA = "3rd"; int a = Integer.parseInt(strA); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 17 Copyright © 2014 by John Wiley & Sons. All rights reserved. 18 InputMismatchException Thrown by Scanner • If the input is not a properly formatted number when calling nextInt or nextDouble method Copyright © 2014 by John Wiley & Sons. All rights reserved. 19 Copyright © 2014 by John Wiley & Sons. All rights reserved. 20 Programming Question Try following to see a InputMismatchException : import java.util.Scanner; public class ExceptionDemo2 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); sc.nextInt(); //supply anything other than a number e.g. q } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 21 Copyright © 2014 by John Wiley & Sons. All rights reserved. 22 NoSuchElelmentException If there is no input at all when you call nextInt or nextDouble, a “no such element exception” occurs. To avoid exceptions, use the hasNextInt method if (in.hasNextInt()) { int value = in.nextInt(); } Copyright © 2014 by John Wiley & Sons. All rights reserved. 23 Programming Question Try following to see a NoSuchElementException: import java.util.Scanner; public class ExceptionDemo3 { public static void main(String args[]) { Scanner sc = new Scanner("2 3"); //string with two ints for(int i=1;i<=3;i++) //try to read 3 ints { sc.nextInt(); } } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 24 Copyright © 2014 by John Wiley & Sons. All rights reserved. 25 NullPointerException Thrown when an application attempts to use null in a case where an object is required. These include: • • • • Calling the instance method of a null object. Accessing or modifying the field of a null object. Taking the length of null as if it were an array. Accessing or modifying the slots of null as if it were an array. Copyright © 2014 by John Wiley & Sons. All rights reserved. 26 Programming Question Try following to see a NullPointerException: import java.util.Scanner; public class ExceptionDemo4 { public static void main(String args[]) { Scanner sc = new Scanner("abc"); sc=null; sc.next(); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 27 Copyright © 2014 by John Wiley & Sons. All rights reserved. 28 Project Phase II Discussion Copyright © 2014 by John Wiley & Sons. All rights reserved. 29 Hierarchy of Exception Classes System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. -LinkageError -VirtualMachineError … Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully. (Fatal) Copyright © 2014 by John Wiley & Sons. All rights reserved. •Used to indicate that exceptional situations have Exception describes errors occurred caused by your program and external circumstances. These errors can be caught and handled by your program.(Non-Fatal) RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors. (from bad programming) 30 Checked Exceptions vs. Unchecked Exceptions Unchecked Exceptions: • RuntimeException, Error and their subclasses • your fault. • The compiler does not check whether you handle an unchecked exception. • typically can be prevented by proper coding Checked Exceptions: • All other exceptions • occurdue to external circumstances that the programmer cannot prevent • The compiler checks that your program handles these exceptions. Copyright © 2014 by John Wiley & Sons. All rights reserved. 31 31 Exception Handling - Throwing Exceptions How to handle error after detection? • Method1: Throw Exception • Method 2: Catch Exception using Try Catch block Copyright © 2014 by John Wiley & Sons. All rights reserved. 32 Throwing an Exception Method1: Throw Exception Throw an exception object to signal an exceptional condition E.g. someone tries to withdraw too much money from a bank account • Throw an IllegalArgumentException • in withdraw method of BankAccount class: Copyright © 2014 by John Wiley & Sons. All rights reserved. 33 Programming Question Modify BankAccount class withdraw method so that it throws an IllegalArgumentException if amount requested is greater than balance. Find program template in next slide Copyright © 2014 by John Wiley & Sons. All rights reserved. 34 public class BankAccount{ private double balance; public BankAccount(double initialBalance) balance = initialBalance; } public void deposit(double amount) balance = balance + amount; } public void withdraw(double amount) balance = balance - amount; } public double getBalance() return balance; { { { { } public static void main(String args[]) { BankAccount account = new BankAccount(1000); account.withdraw(2000); System.out.println("new balance="+account.getBalance()); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 35 Answer BankAccount.java public class BankAccount{ private double balance; public BankAccount(double initialBalance) balance = initialBalance; } public void deposit(double amount) balance = balance + amount; } { { public void withdraw(double amount) { if(amount>balance) throw new IllegalArgumentException("Amount exceeds Balance!"); balance = balance - amount; } public double getBalance() return balance; } { public static void main(String args[]) { BankAccount account = new BankAccount(1000); account.withdraw(2000); System.out.println("new balance="+account.getBalance()); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 36 Copyright © 2014 by John Wiley & Sons. All rights reserved. 37 Question Suppose balance is 100 and amount is 200. What is the value of balance after these statements? if (amount > balance) { throw new IllegalArgumentException("Amount exceeds balance"); } balance = balance – amount; Copyright © 2014 by John Wiley & Sons. All rights reserved. 38 Answer Answer: It is still 100. The last statement was not executed because the exception was thrown. Copyright © 2014 by John Wiley & Sons. All rights reserved. 39 Catching Exceptions Method 2: Catch Exception using Try Catch block • • • • handled exception in your program Place the statements that can cause an exception inside a try block Place handler inside a catch clause. Each catch clause contains a handler. try { String filename ="abc.txt"; Scanner in = new Scanner(new File(filename)); String input = in.next(); int value = Integer.parseInt(input); . . . } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println(exception.getMessage()); } Copyright © 2014 by John Wiley & Sons. All rights reserved. 40 Programming Question Modify Total class to use try/catch statements to handle possible exceptions. • List all thrown Exceptions by checking all method and constructor calls against JavaDoc API • All these exceptions must be caught and handled After try/catch blocks, write a print statement to print “Test code execution after try-catch block” • This code would be executed even when an exception was caught Copyright © 2014 by John Wiley & Sons. All rights reserved. 41 What errors can be thrown? public class Total { public static void main(String[] args) { double total =0; Scanner console = new Scanner(System.in); System.out.print("Input file: "); String inputFileName = console.next(); System.out.print("Output file: "); String outputFileName = console.next(); File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter(outputFileName); while (in.hasNextDouble()) { double value = in.nextDouble(); out.printf("%15.2f\n", value); total = total + value; } out.printf("Total: %8.2f\n", total); in.close(); out.close(); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 42 Answer Total.java public class Total { public static void main(String[] args) { double total =0; Scanner console = new Scanner(System.in); System.out.print("Input file: "); String inputFileName = console.next(); System.out.print("Output file: "); String outputFileName = console.next(); File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter(outputFileName); while (in.hasNextDouble()) { double value = in.nextDouble(); out.printf("%15.2f\n", value); total = total + value; } out.printf("Total: %8.2f\n", total); in.close(); out.close(); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 43 Checked/Unchecked? NoSuchElementException - RuntimeException IllegalStateException - RuntimeException NullPointerException - RuntimeException FileNotFoundException – IOException (Checked Exception) InputMismatchException - RuntimeException IllegalFormatException - RuntimeException Let us handle 2 exceptions Copyright © 2014 by John Wiley & Sons. All rights reserved. 44 Answer public class Total{ public static void main(String[] args) try { double total =0; Total.java { Scanner console = new Scanner(System.in); System.out.print("Input file: "); String inputFileName = console.next(); System.out.print("Output file: "); String outputFileName = console.next(); File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter(outputFileName); while (in.hasNextDouble()) { double value = in.nextDouble(); out.printf("%15.2f\n", value); total = total + value; } out.printf("Total: %8.2f\n", total); in.close(); out.close(); } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println(exception.getMessage()); } System.out.println(“Test code after try catch block”); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. Where are we catching the FileNotFound exception? TODO: 1. Comment catch block of NumberFOrmatException. What happens when you compile? 2. Comment catch block of IOException. What happens when you compile? 3. Include a catch block to handle FileNotFoundException below catch block for IOException. What happens when you compile? 45 Total.java TODO: 1. Comment catch block of NumberFOrmatException. What happens when you compile? Compile successfully 2. Comment catch block of IOException. What happens when you compile? Compiler error occurs 3. Include a catch block to handle FileNotFoundException below catch block for IOException. What happens? Copyright © 2014 by John Wiley & Sons. All rights reserved. Compiler error occurs. Move the catch block above catch block for IOException 46 Copyright © 2014 by John Wiley & Sons. All rights reserved. 47 Catching subclass exceptions • Placing catch blocks for a superclass exception type before other catch blocks that catch subclass exception types would prevent those catch blocks from executing, so a compilation error occurs. Only the First Matching catch Executes • If there are multiple catch blocks that match a particular exception type, only the first matching catch block executes when an exception of that type occurs. Copyright © 2014 by John Wiley & Sons. All rights reserved. 48 Catching Exceptions Three exceptions may be thrown in the try block: • The Scanner constructor can throw a FileNotFoundException. • Scanner.next can throw a NoSuchElementException. • Integer.parseInt can throw a NumberFormatException. If any of these exceptions is actually thrown, then the rest of the instructions in the try block are skipped. Copyright © 2014 by John Wiley & Sons. All rights reserved. 49 Syntax 11.2 Catching Exceptions Copyright © 2014 by John Wiley & Sons. All rights reserved. 50 DivisionByZero – No Exception Handling import java.util.Scanner; public class DivideByZeroNoExceptionHandling { public static int quotient( int numerator, int denominator ) { return numerator / denominator; // possible division by zero } public static void main( String[] args ) { Scanner scanner = new Scanner( System.in ); System.out.print( "Please enter an integer numerator: " ); int numerator = scanner.nextInt(); System.out.print( "Please enter an integer denominator: " ); int denominator = scanner.nextInt(); int result = quotient( numerator, denominator ); System.out.printf("\nResult: %d / %d = %d\n", numerator, denominator, result ); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 51 Copyright © 2014 by John Wiley & Sons. All rights reserved. 52 DivisionByZero – With Exception Handling public class DivideByZeroWithExceptionHandling{ public static int quotient( int numerator, int denominator ) throws ArithmeticException return numerator / denominator; // possible division by zero } { public static void main( String[] args ) { Scanner scanner = new Scanner( System.in ); // scanner for input boolean continueLoop = true; // determines if more input is needed do { try { System.out.print( "Please enter an integer numerator: " ); int numerator = scanner.nextInt(); System.out.print( "Please enter an integer denominator: " ); int denominator = scanner.nextInt(); int result = quotient( numerator, denominator ); System.out.printf( "\nResult: %d / %d = %d\n", numerator, denominator, result ); continueLoop = false; // input successful; end looping } catch ( ArithmeticException arithmeticException ) { System.err.printf( "\nException: %s\n", arithmeticException ); System.out.println("Zero is an invalid denominator. Please try again.\n" ); } } while ( continueLoop ); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 53 Copyright © 2014 by John Wiley & Sons. All rights reserved. 54 DivisionByZero – Avoid Runtime Exception Handling by proper coding import java.util.Scanner; public class DivideByZeroNoExceptionHandling2{ public static int quotient( int numerator, int denominator ) { return numerator / denominator; // possible division by zero } public static void main( String[] args ) { Scanner scanner = new Scanner( System.in ); System.out.print( "Please enter an integer numerator: " ); int numerator = scanner.nextInt(); System.out.print( "Please enter an integer denominator: " ); int denominator = scanner.nextInt(); while(denominator==0) //avoid handling divisionByZero error by proper coding { System.out.println("Zero is an invalid denominator. Please try again.\n" ); System.out.print( "Please enter an integer numerator: " ); numerator = scanner.nextInt(); System.out.print( "Please enter an integer denominator: " ); denominator = scanner.nextInt(); } int result = quotient( numerator, denominator ); System.out.printf( "\nResult: %d / %d = %d\n", numerator, denominator, result ); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 55 Copyright © 2014 by John Wiley & Sons. All rights reserved. 56 Checked Exceptions - throws Sometimes, it's appropriate for code to catch exceptions that can occur within it (try/catch) In other cases, however, it's better to let a method further up the call stack handle the exception. Add a throws clause to the method header E.g. public void readData(String filename) throws FileNotFoundException { File inFile = new File(filename); Scanner in = new Scanner(inFile); . . . } Copyright © 2014 by John Wiley & Sons. All rights reserved. 57 Checked Exceptions - throws The throws clause signals to the caller of your method that it may encounter a FileNotFoundException. • The caller must decide o To handle the exception (try/catch) o Or declare the exception may be thrown (throws) Throw early, catch late • Throw an exception as soon as a problem is detected. • Catch it only when the problem can be handled Copyright © 2014 by John Wiley & Sons. All rights reserved. 58 Syntax 11.3 throws Clause (Unchecked) optional Copyright © 2014 by John Wiley & Sons. All rights reserved. 59 Programming Question Modify the Total3 to use throws clause in writeFileTotal method declaration. Then modify main method to: • (1) throw exceptions at user • (2) handle error in main method using try/catch blocks public class Total3{ public static void main(String[] args){ writeFileTotal(); } public static void writeFileTotal(){ Scanner console = new Scanner(System.in); System.out.print("Input file: "); String inputFileName = console.next(); System.out.print("Output file: "); String outputFileName = console.next(); File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter(outputFileName); while (in.hasNextDouble()){ double value = in.nextDouble(); out.printf("%15.2f\n", value); total = total + value; } out.printf("Total: %8.2f\n", total); in.close(); out.close(); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 60 Option1: Calling methods also throw exception (delegate error): import import import import import java.io.File; java.io.FileNotFoundException; java.io.IOException; java.io.PrintWriter; java.util.Scanner; public class Total3{ public static void main(String[] args) throws IOException{ writeFileTotal(); System.out.println("end of program"); } Copyright © 2014 by John Wiley & Sons. All rights reserved. 61 public static void writeFileTotal() throws FileNotFoundException{ double total = 0; Scanner console = new Scanner(System.in); System.out.print("Input file: "); String inputFileName = console.next(); System.out.print("Output file: "); String outputFileName = console.next(); File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter(outputFileName); while (in.hasNextDouble()){ double value = in.nextDouble(); out.printf("%15.2f\n", value); total = total + value; } out.printf("Total: %8.2f\n", total); in.close(); out.close(); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 62 Copyright © 2014 by John Wiley & Sons. All rights reserved. 63 Answer Option2: calling method use try catch block to internally handle error import import import import import java.io.File; java.io.FileNotFoundException; java.io.IOException; java.io.PrintWriter; java.util.Scanner; public class Total3{ public static void main(String[] args){ try{ writeFileTotal(); } catch(FileNotFoundException exp) { System.out.println("File not found!"); } System.out.println("end of program"); } Copyright © 2014 by John Wiley & Sons. All rights reserved. 64 public static void writeFileTotal() throws FileNotFoundException{ double total = 0; Scanner console = new Scanner(System.in); System.out.print("Input file: "); String inputFileName = console.next(); System.out.print("Output file: "); String outputFileName = console.next(); File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter(outputFileName); while (in.hasNextDouble()){ double value = in.nextDouble(); out.printf("%15.2f\n", value); total = total + value; } out.printf("Total: %8.2f\n", total); in.close(); out.close(); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 65 Copyright © 2014 by John Wiley & Sons. All rights reserved. 66 The finally Clause A try block may optionally have a finally block associated with it. If provided, a finally block follows any catch blocks associated with that same try block. try{ … } catch(FileNotFoundException e){ … } catch(IOException e){ … } finally{ … } Copyright © 2014 by John Wiley & Sons. All rights reserved. 67 The finally Clause Use finally block when you do some clean up • Example - closing files PrintWriter out = new PrintWriter(filename); try { writeData(out); } catch(IOException e) { e.printStackTrace(); } finally { out.close(); } Executes the close even if an exception is thrown. Copyright © 2014 by John Wiley & Sons. All rights reserved. 68 The code within a finally block is guaranteed to execute no matter what happens in the try/catch code that precedes it: • The try block executes to completion without throwing any exceptions whatsoever. • The try block throws an exception that is handled by one of the catch blocks. • The try block throws an exception that is not handled by any of the catch blocks Copyright © 2014 by John Wiley & Sons. All rights reserved. 69 Syntax 11.4 finally Clause Copyright © 2014 by John Wiley & Sons. All rights reserved. 70 Designing Your Own Exception Types You can design your own exception types • subclasses of Exception or RuntimeException. Throw an InsufficientFundsException when the amount to withdraw an amount from a bank account exceeds the current balance. if (amount > balance) { throw new InsufficientFundsException( "withdrawal of " + amount + " exceeds balance of " + balance); } Make InsufficientFundsException an unchecked exception • Extend RuntimeException or one of its subclasses Copyright © 2014 by John Wiley & Sons. All rights reserved. 71 Designing Your Own Exception Types Supply two constructors for the class • A constructor with no arguments • A constructor that accepts a message string describing reason for exception public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {} public InsufficientFundsException(String message) { super(message); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 72 Programming Question Implement InsufficientFundsException class Modify BankAccount class to throw this exception when withdrawal amount exceeds balance. Copyright © 2014 by John Wiley & Sons. All rights reserved. 73 Answer InsufficientFundsException.java public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {} public InsufficientFundsException(String message) { super(message); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 74 Answer public class BankAccount{ private double balance; public BankAccount(double initialBalance) balance = initialBalance; } public void deposit(double amount) balance = balance + amount; } { { public void withdraw(double amount) { if(amount>balance) throw new InsufficientFundsException("Amount exceeds Balance!"); balance = balance - amount; } public double getBalance() return balance; } { public static void main(String args[]) { BankAccount account = new BankAccount(1000); account.withdraw(2000); System.out.println("new balance="+account.getBalance()); } } Copyright © 2014 by John Wiley & Sons. All rights reserved. 75 Copyright © 2014 by John Wiley & Sons. All rights reserved. 76