Presentation is loading. Please wait.

Presentation is loading. Please wait.

Goals To read and write text files To process command line arguments

Similar presentations


Presentation on theme: "Goals To read and write text files To process command line arguments"— Presentation transcript:

1

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 Read Text Files Read Text Files:
Use Scanner class for reading text files To read from a disk file: Construct a File object representing the input file File inputFile = new File(“data.txt"); Use this File object to construct a Scanner object: Scanner in = new Scanner(inputFile); Use the Scanner methods to read data from file next(), nextInt(), and nextDouble()

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

5 Example

6 Write to a file Write to a file: Construct a PrintWriter object:
PrintWriter out = new PrintWriter("output.txt"); If file already exists, it is emptied before the new data are written into it. If file doesn't exist, an empty file is created. Use print and println to write into a PrintWriter: out.println("Hello, World!"); out.printf("Total: %8.2f\n", total);

7 Write to a file 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. Always specify "UTF-8" as the second parameter when construction a Scanner or a PrintWriter.

8 Example

9 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. input.txt 32.00 54.00 67.50 29.00 35.00 80.00 115.00 44.50 100.00 65.00 Total: Program template in next slide

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

11 Answer Total.java 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();

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

13 Answer Answer: The program throws a FileNotFoundException and terminates.

14 FileNotFoundException
When the input or output file doesn't exist, a FileNotFoundException can occur. public PrintWriter(File file) throws FileNotFoundException: FileNotFoundException - If the given file object does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file

15 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"); } public PrintWriter(File file) throws FileNotFoundException: FileNotFoundException - If the given file object does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file

16 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

17 Answer If the input is not a properly formatted number when calling parseInt or parseDouble method NumberFormatException occurs

18 Example

19 InputMismatchException
Thrown by Scanner If the input is not a properly formatted number when calling nextInt or nextDouble method

20

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

22

23 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(); }

24 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(); }

25

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

27 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(); }

28

29 Hierarchy of Exception Classes
Used to indicate that exceptional situations have occurred Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.(Non-Fatal) 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) RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors. (from bad programming)

30

31 Checked Exceptions vs. 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.

32 Question Is FileNotFoundException a checked or unchecked exception?

33 Answer Checked Exception Why?
-Not an Error and is not a subclass of java.lang.RuntimeException

34 Exception Handling - Throwing Exceptions
How to handle error after detection? Method1: Throw Exception Method 2: Catch Exception using Try Catch block

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

36 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

37 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());

38 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());

39

40 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;

41 Answer Answer: It is still 100. The last statement was not executed because the exception was thrown.

42 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()); public File(String pathname) Throws: NullPointerException - If the pathname argument is null Runtime exception – so not handled public Scanner(File source) throws FileNotFoundException IOException – so should be handled public String next() Throws: NoSuchElementException - if no more tokens are available Throws:IllegalStateException - if this scanner is closed public static int parseInt(String s) Throws: NumberFormatException - if the string does not contain a parsable integer.

43 Catching Exceptions Which exceptions coud be thrown? try {
String filename ="abc.txt"; Scanner in = new Scanner(new File(filename)); //FileNotFoundException (C)-required to have a catch clause String input = in.next(); //NoSuchElementException(U), IllegalStateException (U) //catch clause optional int value = Integer.parseInt(input);//NumberFormatException (U) . . . } catch (IOException exception) exception.printStackTrace(); catch (NumberFormatException exception) System.out.println(exception.getMessage()); U- UNCHECKED EXCEPTION C- CHECKED EXCEPTION public File(String pathname) Throws: NullPointerException - If the pathname argument is null Runtime exception – so not handled public Scanner(File source) throws FileNotFoundException IOException – so should be handled public String next() Throws: NoSuchElementException - if no more tokens are available Throws:IllegalStateException - if this scanner is closed public static int parseInt(String s) Throws: NumberFormatException - if the string does not contain a parsable integer.

44 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

45 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();

46 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();

47 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

48 Answer Total.java Where are we catching the FileNotFound exception?
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”); Where are we catching the FileNotFound exception? TODO: Comment catch block of NumberFOrmatException. What happens when you compile? Comment catch block of IOException. What happens when you compile? Include a catch block to handle FileNotFoundException below catch block for IOException. What happens when you compile?

49 Total.java TODO: Comment catch block of NumberFOrmatException. What happens when you compile? Comment catch block of IOException. What happens when you compile? 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

50

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

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

53 Syntax 11.2 Catching Exceptions

54 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");

55 If the exception thrown is caught by one of catch blocks, exception
is printed and program continues execution rest of the program as usual

56 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");

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

58 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 );

59

60 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 );

61

62 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" ); numerator = scanner.nextInt(); denominator = scanner.nextInt(); int result = quotient( numerator, denominator ); System.out.printf( "\nResult: %d / %d = %d\n", numerator, denominator, result );

63

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

65 Checked Exceptions - throws
The throws clause signals to the caller of your method that it may encounter a FileNotFoundException. The caller must decide To handle the exception (try/catch) 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

66 Syntax 11.3 throws Clause (Unchecked) optional

67 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();

68 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"); }

69 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();

70

71 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");

72 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();

73

74 Project Phase II Discussion

75 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{

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

77 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

78 Syntax 11.4 finally Clause

79 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

80 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); } When the exception is caught, its message string can be retrieved Using the getMessage method of the Throwable class.

81 Programming Question Implement InsufficientFundsException class
Modify BankAccount class to throw this exception when withdrawal amount exceeds balance.

82 Answer InsufficientFundsException.java
public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {} public InsufficientFundsException(String message) super(message); }

83 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());

84


Download ppt "Goals To read and write text files To process command line arguments"

Similar presentations


Ads by Google