Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Input/Output and Exception Handling.

Similar presentations


Presentation on theme: "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Input/Output and Exception Handling."— Presentation transcript:

1 Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Input/Output and Exception Handling

2 Copyright © 2014 by John Wiley & Sons. All rights reserved.2 Goals  To read and write text files  To process command line arguments  To throw and catch exceptions  To implement programs that propagate checked exceptions

3 Copyright © 2014 by John Wiley & Sons. All rights reserved.3 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(“data.txt"); 2.Use this File object to construct a Scanner object: Scanner in = new Scanner(inputFile); 3.Use the Scanner methods to read data from file next(), nextInt(), and nextDouble()

4 Copyright © 2014 by John Wiley & Sons. All rights reserved.4 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. }  Close the scanner in.close()

5 Copyright © 2014 by John Wiley & Sons. All rights reserved.5 Example

6 Copyright © 2014 by John Wiley & Sons. All rights reserved.6 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);

7 Copyright © 2014 by John Wiley & Sons. All rights reserved.7 Example

8 Copyright © 2014 by John Wiley & Sons. All rights reserved.8 Formatted Output – printf statement  Use the printf method to specify how values should be formatted.  Suppose you have a variable price with value 1.215962441314554  If you use System.out.println(price) Will print : 1.215962441314554  If you want a formatted output(e.g. only 2 decimal points displayed): System.out.printf("%.2f", price); Will print: 1.22

9 Copyright © 2014 by John Wiley & Sons. All rights reserved.9 Example

10 Copyright © 2014 by John Wiley & Sons. All rights reserved.10 Formatted Output  You can also specify a field width: System.out.printf("%10.2f", price); This prints 10 characters, six spaces followed by the four characters 1.22  This command System.out.printf("Price per liter:%10.2f", price); Prints Price per liter: 1.22

11 Copyright © 2014 by John Wiley & Sons. All rights reserved.11 Example

12 Copyright © 2014 by John Wiley & Sons. All rights reserved.12 Formatted Output

13 Copyright © 2014 by John Wiley & Sons. All rights reserved.13 Example

14 Copyright © 2014 by John Wiley & Sons. All rights reserved.14 Formatted Output  You can print multiple values with a single call to the printf method.  Example System.out.printf("Quantity: %d Total: %10.2f",quantity, total);  Output explained:

15 Copyright © 2014 by John Wiley & Sons. All rights reserved.15 Write to a file 3.You must close a file when you are done processing it: in.close(); //close scanner out.close(); //close printwriter Otherwise, not all of the output may be written to the disk file.

16 Copyright © 2014 by John Wiley & Sons. All rights reserved.16 Example

17 Copyright © 2014 by John Wiley & Sons. All rights reserved.17 Programming Question  Read a file input.txt containing numbers  Write the numbers in a column followed by their total in a file output.txt: Hint: use printf statements to write to file. 32 54 67.5 29 35 80 115 44.5 100 65 input.txt Program template in next slide 32.00 54.00 67.50 29.00 35.00 80.00 115.00 44.50 100.00 65.00 Total: 622.00

18 Copyright © 2014 by John Wiley & Sons. All rights reserved.18 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 }

19 Copyright © 2014 by John Wiley & Sons. All rights reserved.19 Answer import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import 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(); } Total.java

20 Copyright © 2014 by John Wiley & Sons. All rights reserved.20 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.

21 Copyright © 2014 by John Wiley & Sons. All rights reserved.21 Answer Answer: The program throws a FileNotFoundException and terminates.

22 Copyright © 2014 by John Wiley & Sons. All rights reserved.22 FileNotFoundException  When the input or output file doesn't exist, a FileNotFoundException can occur.

23 Copyright © 2014 by John Wiley & Sons. All rights reserved.23 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"); … }

24 Copyright © 2014 by John Wiley & Sons. All rights reserved.24 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 Integer.parseInt with improperly formatted numbers

25 Copyright © 2014 by John Wiley & Sons. All rights reserved.25 Answer If the input is not a properly formatted number when calling parseInt or parseDouble method NumberFormatException occurs

26 Copyright © 2014 by John Wiley & Sons. All rights reserved.26 Example

27 Copyright © 2014 by John Wiley & Sons. All rights reserved.27 InputMismatchException  Thrown by Scanner If the input is not a properly formatted number when calling nextInt or nextDouble method

28 Copyright © 2014 by John Wiley & Sons. All rights reserved.28

29 Copyright © 2014 by John Wiley & Sons. All rights reserved.29 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 }

30 Copyright © 2014 by John Wiley & Sons. All rights reserved.30

31 Copyright © 2014 by John Wiley & Sons. All rights reserved.31 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(); }

32 Copyright © 2014 by John Wiley & Sons. All rights reserved.32 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(); }

33 Copyright © 2014 by John Wiley & Sons. All rights reserved.33

34 Copyright © 2014 by John Wiley & Sons. All rights reserved.34 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.

35 Copyright © 2014 by John Wiley & Sons. All rights reserved.35 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(); }

36 Copyright © 2014 by John Wiley & Sons. All rights reserved.36

37 Copyright © 2014 by John Wiley & Sons. All rights reserved.37 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) Exception describes errors 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) Used to indicate that exceptional situations have occurred

38 Copyright © 2014 by John Wiley & Sons. All rights reserved.38

39 Copyright © 2014 by John Wiley & Sons. All rights reserved.39 Checked Exceptions vs. Unchecked Exceptions  Unchecked Exceptions: RuntimeException, Error and their subclasses The compiler does not check whether you handle an unchecked exception. Run time exceptions are your fault. typically can be prevented by proper coding  Checked Exceptions: All other exceptions occur due to external circumstances that the programmer cannot prevent invalid user input, database problems, absent files The compiler checks that your program handles these exceptions. 39

40 Copyright © 2014 by John Wiley & Sons. All rights reserved.40 Question  Is FileNotFoundException a checked or unchecked exception?

41 Copyright © 2014 by John Wiley & Sons. All rights reserved.41 Answer  Checked Exception  Why? -Not an Error and is not a subclass of java.lang.RuntimeException

42 Copyright © 2014 by John Wiley & Sons. All rights reserved.42 Example

43 Copyright © 2014 by John Wiley & Sons. All rights reserved.43 Exception Handling - Throwing Exceptions  How to handle error after detection? Method1: Throw Exception Method 2: Catch Exception using Try Catch block

44 Copyright © 2014 by John Wiley & Sons. All rights reserved.44 Throwing an Exception  Method1: Throw Exception  Throw an exception object to signal an exceptional condition  EXAMPLE1:

45 Copyright © 2014 by John Wiley & Sons. All rights reserved.45 Throwing an Exception  EXAMPLE2:  BankAccount.java – withdraw method someone tries to withdraw too much money from a bank account Throw an IllegalArgumentException in withdraw method of BankAccount class:

46 Copyright © 2014 by John Wiley & Sons. All rights reserved.46 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

47 Copyright © 2014 by John Wiley & Sons. All rights reserved.47 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()); } }

48 Copyright © 2014 by John Wiley & Sons. All rights reserved.48 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 IllegalArgumentException("Amount exceeds Balance!"); balance = balance - amount; } public double getBalance() { return balance; } public static void main(String args[]) { BankAccount account = new BankAccount(1000); System.out.println("previous balance="+account.getBalance()); account.withdraw(2000); System.out.println("new balance="+account.getBalance()); } } BankAccount.java

49 Copyright © 2014 by John Wiley & Sons. All rights reserved.49 Not executed

50 Copyright © 2014 by John Wiley & Sons. All rights reserved.50 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;

51 Copyright © 2014 by John Wiley & Sons. All rights reserved.51 Answer Answer: It is still 100. The last statement was not executed because the exception was thrown.

52 Copyright © 2014 by John Wiley & Sons. All rights reserved.52 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) //1catch clause catches 1 exception { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println(exception.getMessage()); }

53 Copyright © 2014 by John Wiley & Sons. All rights reserved.53 Example public class BankAccount{. 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); System.out.println("previous balance="+account.getBalance()); try { account.withdraw(2000); } catch(IllegalArgumentException e) { e. printStackTrace(); } System.out.println("new balance="+account.getBalance()); } How does the output change?

54 Copyright © 2014 by John Wiley & Sons. All rights reserved.54 Complete Example 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); System.out.println("previous balance="+account.getBalance()); //account.withdraw(2000); //throws version try //try-catch version { account.withdraw(2000); } catch(IllegalArgumentException e) { e. printStackTrace(); } System.out.println("new balance="+account.getBalance()); }

55 Copyright © 2014 by John Wiley & Sons. All rights reserved.55 output...... Statements after try/catch block are executed even if error is thrown

56 Copyright © 2014 by John Wiley & Sons. All rights reserved.56 Catching Exceptions  Which exceptions coud be thrown? Which ones are checked/unchecked? 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()); }

57 Copyright © 2014 by John Wiley & Sons. All rights reserved.57 Catching Exceptions  what exceptions could be thrown? try { String filename ="abc.txt"; Scanner in = new Scanner(new File(filename)); String input = in.next(); int value = Integer.parseInt(input);... } UNCHECKED – catch clause is optional CHECKED-required to have a catch clause UNCHECKED – catch clause is optional

58 Copyright © 2014 by John Wiley & Sons. All rights reserved.58 Catching Exceptions  Does this catch the required FileNotFoundException? 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()); }

59 Copyright © 2014 by John Wiley & Sons. All rights reserved.59 Catching Exceptions  Yes. try { String filename ="abc.txt"; Scanner in = new Scanner(new File(filename)); String input = in.next(); int value = Integer.parseInt(input);... } catch (IOException exception) //catch FileNotFoundException { exception.printStackTrace(); } catch (NumberFormatException exception)//unchecked exception catch { System.out.println(exception.getMessage()); }

60 Copyright © 2014 by John Wiley & Sons. All rights reserved.60 Programming Question  Total2.java 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

61 Copyright © 2014 by John Wiley & Sons. All rights reserved.61 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(); } What errors can be thrown?

62 Copyright © 2014 by John Wiley & Sons. All rights reserved.62 Answer 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(); } Total.java

63 Copyright © 2014 by John Wiley & Sons. All rights reserved.63 Checked/Unchecked?  NoSuchElementException - RuntimeException  IllegalStateException - RuntimeException  NullPointerException - RuntimeException  FileNotFoundException – IOException (Checked Exception)  InputMismatchException - RuntimeException  IllegalFormatException - RuntimeException  Can you rewrite Total.java to handle 2 exceptions

64 Copyright © 2014 by John Wiley & Sons. All rights reserved.64 Answer public class Total{ public static void main(String[] args) { try { 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(); } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println(exception.getMessage()); } System.out.println(“Test code after try catch block”); } Total.java 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?

65 Copyright © 2014 by John Wiley & Sons. All rights reserved.65 Total.java 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? Compile successfully Compiler error occurs Compiler error occurs. Move the catch block above catch block for IOException

66 Copyright © 2014 by John Wiley & Sons. All rights reserved.66

67 Copyright © 2014 by John Wiley & Sons. All rights reserved.67  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.

68 Copyright © 2014 by John Wiley & Sons. All rights reserved.68 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.

69 Copyright © 2014 by John Wiley & Sons. All rights reserved.69 Syntax 11.2 Catching Exceptions

70 Copyright © 2014 by John Wiley & Sons. All rights reserved.70 Question  What happens in the following program if you give a invalid input E.g try anything other than a number import java.util.Scanner; import java.io.*; import java.util.InputMismatchException; public class ExceptionDemo { public static void main(String args[]) { try { Scanner sc = new Scanner(System.in); sc.nextInt(); //supply anything other than a number e.g. q } catch(InputMismatchException e) { e. printStackTrace(); } System.out.println("end of demo"); }

71 Copyright © 2014 by John Wiley & Sons. All rights reserved.71 If the exception thrown is caught by one of catch blocks, exception is printed and program continues execution rest of the program as usual

72 Copyright © 2014 by John Wiley & Sons. All rights reserved.72 Question  What happens in the following program if you give a invalid input E.g try c import java.util.Scanner; import java.io.*; public class ExceptionDemo { public static void main(String args[]) { try { Scanner sc = new Scanner(System.in); sc.nextInt(); //supply anything other than a number e.g. q } catch(NumberFormatException e) { e. printStackTrace(); } System.out.println("end of demo"); }

73 Copyright © 2014 by John Wiley & Sons. All rights reserved.73 Answer If the exception thrown is not caught by one of catch blocks, exception is thown at user and program stop executing after that point.

74 Copyright © 2014 by John Wiley & Sons. All rights reserved.74 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 ); }

75 Copyright © 2014 by John Wiley & Sons. All rights reserved.75

76 Copyright © 2014 by John Wiley & Sons. All rights reserved.76 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 ); }

77 Copyright © 2014 by John Wiley & Sons. All rights reserved.77

78 Copyright © 2014 by John Wiley & Sons. All rights reserved.78 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 ); }

79 Copyright © 2014 by John Wiley & Sons. All rights reserved.79

80 Copyright © 2014 by John Wiley & Sons. All rights reserved.80 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);... }

81 Copyright © 2014 by John Wiley & Sons. All rights reserved.81 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

82 Copyright © 2014 by John Wiley & Sons. All rights reserved.82 Syntax 11.3 throws Clause (Unchecked) optional

83 Copyright © 2014 by John Wiley & Sons. All rights reserved.83 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(); }

84 Copyright © 2014 by John Wiley & Sons. All rights reserved.84  Option1: Calling methods also throw exception (delegate error): import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Total3{ public static void main(String[] args) throws IOException{ writeFileTotal(); System.out.println("end of program"); }

85 Copyright © 2014 by John Wiley & Sons. All rights reserved.85 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(); }

86 Copyright © 2014 by John Wiley & Sons. All rights reserved.86

87 Copyright © 2014 by John Wiley & Sons. All rights reserved.87 Answer  Option2: calling method use try catch block to internally handle error import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import 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"); }

88 Copyright © 2014 by John Wiley & Sons. All rights reserved.88 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(); }

89 Copyright © 2014 by John Wiley & Sons. All rights reserved.89

90 Copyright © 2014 by John Wiley & Sons. All rights reserved.90 Project Phase II Discussion

91 Copyright © 2014 by John Wiley & Sons. All rights reserved.91 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{ … }

92 Copyright © 2014 by John Wiley & Sons. All rights reserved.92 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.

93 Copyright © 2014 by John Wiley & Sons. All rights reserved.93  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

94 Copyright © 2014 by John Wiley & Sons. All rights reserved.94 Syntax 11.4 finally Clause

95 Copyright © 2014 by John Wiley & Sons. All rights reserved.95 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

96 Copyright © 2014 by John Wiley & Sons. All rights reserved.96 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); } }

97 Copyright © 2014 by John Wiley & Sons. All rights reserved.97 Programming Question  Implement InsufficientFundsException class  Modify BankAccount class to throw this exception when withdrawal amount exceeds balance.

98 Copyright © 2014 by John Wiley & Sons. All rights reserved.98 Answer public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {} public InsufficientFundsException(String message) { super(message); } InsufficientFundsException.java

99 Copyright © 2014 by John Wiley & Sons. All rights reserved.99 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()); }

100 Copyright © 2014 by John Wiley & Sons. All rights reserved.100


Download ppt "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Input/Output and Exception Handling."

Similar presentations


Ads by Google