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

Slides:



Advertisements
Similar presentations
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Advertisements

Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
CS102--Object Oriented Programming
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
COMP 121 Week 5: Exceptions and Exception Handling.
Chapter 9 Exception Handling. Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Chapter 11.  Data is often stored in files such as a text file  We need to read that data into our program  Simplest mechanism  Scanner class  First.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 11 – Input/Output and Exception Handling.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
Chapter 11  I/O and Exception Handling 1 Chapter 11 I/O and Exception Handling.
Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Lecture 7 File I/O (and a little bit about exceptions)‏
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
Files and Streams CS 21a Chapter 11 of Horstmann.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Eleven: Input/Ouput and Exception Handling.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Copyright © 2013 by John Wiley & Sons. All rights reserved. INPUT/OUTPUT AND EXCEPTION HANDLING CHAPTER Slides by Donald W. Smith TechNeTrain.com 7 Final.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 11 – Input/Output and Exception Handling.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Exceptions Handling the unexpected. RHS – SWC 2 The Real World So far, most of our code has been somewhat näive We have assumed that nothing goes wrong…
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Chapter 10 – Input/Output and Exception Handling Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Week 12 – Text Files Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Java Programming Week 9: Input/Ouput and Exception Handling, Files and Streams (Chapter 11 and Chapter 19)
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Input/Output and Exception Handling.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Exception Handling.
Chapter 12 Exception Handling And Text IO
Introduction Exception handling Exception Handles errors
CSE 501N Fall ’09 17: Exception Handling
Chapter 11 – Input/Output and Exception Handling
Goals To read and write text files To process command line arguments
Chapter 11 – Input/Output and Exception Handling
INPUT/OUTPUT AND EXCEPTION HANDLING
Chapter 15 – Exception Handling
Advanced Java Programming
Exceptions Handling the unexpected
CSS 161: Fundamentals of Computing
Chapter 12 Exception Handling
Exception Handling and Reading / Writing Files
Exception Handling.
Chapter 11 Input/Output Exception Handling
Chapter 12 Exception Handling and Text IO Part 1
Presentation transcript:

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

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

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

Copyright © 2014 by John Wiley & Sons. All rights reserved.5 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.6 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.7 FileNotFoundException  When the input or output file doesn't exist, a FileNotFoundException can occur.

Copyright © 2014 by John Wiley & Sons. All rights reserved.8 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.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 Program template in next slide Total:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Copyright © 2014 by John Wiley & Sons. All rights reserved.32 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.33 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.34 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.35 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.36 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); account.withdraw(2000); System.out.println("new balance="+account.getBalance()); } } BankAccount.java

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

Copyright © 2014 by John Wiley & Sons. All rights reserved.38 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.39 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.40 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.41 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.42 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?

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

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

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

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

Copyright © 2014 by John Wiley & Sons. All rights reserved.48  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.49 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.50 Syntax 11.2 Catching Exceptions

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

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

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

Copyright © 2014 by John Wiley & Sons. All rights reserved.57 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.58 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.59 Syntax 11.3 throws Clause (Unchecked) optional

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

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

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

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

Copyright © 2014 by John Wiley & Sons. All rights reserved.67 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.68 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.69  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.70 Syntax 11.4 finally Clause

Copyright © 2014 by John Wiley & Sons. All rights reserved.71 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.72 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.73 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.74 Answer public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {} public InsufficientFundsException(String message) { super(message); } InsufficientFundsException.java

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