1 / 82

Chapter 11 I/O and Exception Handling

Chapter 11 I/O and Exception Handling. Chapter Goals. To learn how to read and write text files To learn how to throw exceptions To be able to design your own exception classes To understand the difference between checked and unchecked exceptions To learn how to catch exceptions

jacobr
Download Presentation

Chapter 11 I/O and Exception Handling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 11I/O and Exception Handling

  2. Chapter Goals • To learn how to read and write text files • To learn how to throw exceptions • To be able to design your own exception classes • To understand the difference between checked and unchecked exceptions • To learn how to catch exceptions • To know when and where to catch an exception

  3. Reading Text Files • Simplest way to read text: use Scanner class • To read from a disk file, construct a FileReader • Then, use FileReader to construct Scanner object Use the Scanner methods to read data from file • next, nextLine, nextInt and nextDouble FileReader reader = new FileReader("input.txt"); Scanner in = new Scanner(reader);

  4. Writing Text Files • To write to a file, use a PrintWriter object • 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 PrintWriter out = new PrintWriter("output.txt");

  5. Writing Text Files • Use print and println to write to a PrintWriter • You must close a file when you are done processing it • Otherwise, not all of the output may be written to the disk file out.println(29.95); out.println(new Rectangle(5, 10, 15, 25)); out.println("Hello, World!"); out.close();

  6. A Sample Program • Reads all lines of a file and sends them to the output file, preceded by line numbers • Sample input file Mary had a little lamb Whose fleece was white as snow. And everywhere that Mary went, The lamb was sure to go!

  7. A Sample Program • The program produces the output file • This program can be used to number the lines of Java source files /* 1 */ Mary had a little lamb /* 2 */ Whose fleece was white as snow. /* 3 */ And everywhere that Mary went, /* 4 */ The lamb was sure to go!

  8. File LineNumberer.java 01: import java.io.FileReader; 02: import java.io.IOException; 03: import java.io.PrintWriter; 04: import java.util.Scanner; 05: 06:public class LineNumberer 07: { 08:public static void main(String[] args) 09: { 10: Scanner console = new Scanner(System.in); 11: System.out.print("Input file: "); 12: String inputFileName = console.next(); 13: System.out.print("Output file: "); 14: String outputFileName = console.next(); 15: 16:try 17: { Continued…

  9. File LineNumberer.java 18: FileReader reader = new FileReader(inputFileName); 19: Scanner in = new Scanner(reader); 20: PrintWriter out = new PrintWriter(outputFileName); 21:int lineNumber = 1; 22: 23:while (in.hasNextLine()) 24: { 25: String line = in.nextLine(); 26: out.println("/* " + lineNumber + " */ " + line); 27: lineNumber++;28: } 29: 30: out.close(); 31: } 32:catch (IOException exception) 33: { Continued…

  10. File LineNumberer.java 34: System.out.println("Error processing file:" + exception); 35: } 36: } 37: }

  11. Self Check • What happens when you supply the same name for the input and output files to the LineNumberer program? • What happens when you supply the name of a nonexistent input file to the LineNumberer program?

  12. Answers • When the PrintWriter object is created, the output file is emptied, which is the same file as the input file. The input file is now empty and the while loop exits immediately. • The program catches a FileNotFoundException, prints an error message, and terminates.

  13. Command Line Arguments • Three different ways to run a program • Select “run” in compile environment • Click an icon • Type program name in terminal window • Last method is called invoking the program from a command line • When program is invoked from command line, you can provide more info to the program

  14. Command Line Arguments • Programs accept command line arguments • For example, program could be written to allow user to specify input and output files on command line: • Command line arguments are are placed in args parameter of main • In this example • args[0] is “input.txt” • args[1] is “output.txt” java LineNumberer input.txt output.txt

  15. Command Line Arguments • It is up to the programmer to decide what to do with command line arguments • It is customary to interpret arguments as follows • If it starts with a hyphen, it is an option • If it does not start with a hyphen, it is a file name • For example, could use -c if comment delimiters are desired (e.g., if file is a program) java LineNumberer -c HelloWorld.java HelloWorld.txt

  16. Command Line Arguments • Example for(String a : args) { if(a.startsWith(“-”)) // It’s an option { if (a.equals(“-c”) useCommentDelimiters = true; } else if (inputFileName == null) inputFileName = a; else if (outputFileName == null) outputFileName = a; }

  17. Command Line Arguments • Are command line arguments a good idea? • It depends… • For casual or infrequent use, graphical user interface (GUI) is much better • But for frequent use, GUI has some drawbacks • For example, hard to automate, so it is hard to write a script to automate tasks

  18. Therac-25 Incident • Computerized device used for radiation treatment • Between 1985 and 1987 at least 6 people got severe overdoses, some died • Cause was a bug in the program that controlled the machine • See the text

  19. Error Handling • Traditional approach: • Method returns error code • Problem: Might forget to check for error • Failure notification may go undetected • Problem: Calling method may not be able to do anything about failure • Program must fail --- let its caller worry about it • Many method calls would need to be checked

  20. Error Handling • Instead of programming for success… • …you would always program for failure • But this might make code hard to read x.doSomething() if (!x.doSomething()) return false;

  21. Throwing Exceptions • In Java: Exceptions • Cannot be overlooked • Sent directly to an exception handler, not just caller of failed method • “Throw” an exception object to signal an exceptional condition • Example: IllegalArgumentException // illegal parameter valueIllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception;

  22. Throwing Exceptions • No need to store exception object in variable • When an exception is thrown, method terminates immediately • Execution continues with an exception handler throw new IllegalArgumentException("Amount exceeds balance");

  23. Example public class BankAccount { public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; } balance = balance - amount; } . . . }

  24. Hierarchy of Exception Classes Figure 1:The Hierarchy of Exception Classes

  25. Syntax 15.1: Throwing an Exception  throw exceptionObject; Example:  throw new IllegalArgumentException(); Purpose: To throw an exception and transfer control to a handler for this exception type

  26. Self Check • How should you modify the deposit method to ensure that the balance is never negative? • Suppose you modify withdraw to throw exception if balance is negative. Then you construct a new bank account object with a zero balance and call withdraw(10). What is the value of balance afterwards?

  27. Answers • Throw an exception if the amount being deposited is less than zero. • The balance is still zero because the last statement of the withdraw method was never executed.

  28. Checked and Unchecked Exceptions • Two types of exceptions: • checked and unchecked • Checked exceptions • The compiler checks that you don't ignore them • Caused by external circumstances that the programmer cannot prevent • Majority occur when dealing with I/O • For example, IOException

  29. Checked and Unchecked Exceptions • Two types of exceptions: checked, unchecked • Unchecked exceptions • Extend the class RuntimeException or Error • They are the programmer's “fault” • Examples of runtime exceptions • Example of error: OutOfMemoryError NumberFormatException IllegalArgumentException NullPointerException

  30. Checked and Unchecked Exceptions • Categories are not perfect • Scanner.nextInt throws unchecked InputMismatchException • Programmer cannot prevent users from entering incorrect input • This choice makes the class easy to use for beginning programmers • Checked exceptions arise mostly when programming with files and streams

  31. Checked and Unchecked Exceptions • For example, use a Scanner to read a file • But, FileReader constructor can throw a FileNotFoundException String filename = . . .; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader);

  32. Checked and Unchecked Exceptions • Two choices… • Handle the exception or • Tell compiler that you want method to be terminated when the exception occurs • Use throws specifier; method throws a checked exception public void read(String filename) throws FileNotFoundException { FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); . . . }

  33. Checked and Unchecked Exceptions • For multiple exceptions, use commas • Exception inheritance hierarchy: for example, if method can throw an IOException and FileNotFoundException, only use IOException • Better to just throw exception than to handle it incompetently public void read(String filename) throws IOException, ClassNotFoundException

  34. Syntax 15.2: Exception Specification accessSpecifier returnType methodName(parameterType parameterName, . . .) throws ExceptionClass, ExceptionClass, . . . Example:  public void read(BufferedReader in) throws IOException Purpose: To indicate the checked exceptions that this method can throw

  35. Self Check • Suppose a method calls the FileReader constructor and the readmethod of the FileReader class, which can throw an IOException. Which throws specification should you use? • Why is a NullPointerException not a checked exception?

  36. Answer • The specification throws IOException is sufficient since FileNotFoundException is a subclass of IOException • Because programmers should simply check for null pointers instead of trying to handle a NullPointerException

  37. Catching Exceptions • Install an exception handler with try/catch statement • tryblock contains statements that may cause an exception • catch clause contains handler for an exception type

  38. Catching Exceptions • Consider this example • Three possible exceptions • FileReader can throw FileNotFoundException • Scanner.Next can throw NoSuchElementException • Integer.parseInt throws NumberFormatException String filename = . . .; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); String input = in.next(); int value = Integer.parseInt(input); . . .

  39. Catching Exceptions try { String filename = . . .; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); String input = in.next(); int value = Integer.parseInt(input); . . . } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println("Input was not a number");} • Example oftry, catch

  40. Catching Exceptions • Statements in try block are executed • If no exceptions occur, catch clauses are skipped • If exception of matching type occurs, executionjumps to catch clause • If exception of another type occurs, it is thrown, to be caught by another try block

  41. Catching Exceptions • catch (IOException exception) • exception contains reference to the exception object that was thrown • catchclause can analyze object to find out more details • exception.printStackTrace() printout of chain of method calls that lead to exception

  42. Syntax 15.3: General Try Block try { statement statement . . . } catch (ExceptionClass exceptionObject) { statement statement . . . } catch (ExceptionClass exceptionObject) { statement statement . . . } . . . Continued…

  43. Syntax 15.3: General Try Block Example: try { System.out.println("How old are you?"); int age = in.nextInt(); System.out.println("Next year, you'll be " + (age + 1)); } catch (InputMismatchException exception) { exception.printStackTrace(); } Purpose: To execute one or more statements that may generate exceptions. If an exception occurs and it matches one of the catch clauses, execute the first one that matches. If no exception occurs, or an exception is thrown that doesn't match any catch clause, then skip the catch clauses.

  44. Self Check • Suppose the file with the given file name exists and has no contents. Trace the flow of execution in the try block in this section. • Is there a difference between catching checked and unchecked exceptions?

  45. Answers • The FileReaderconstructor succeeds, and it is constructed. Then the call in.next() throws a NoSuchElementException, and the tryblock is terminated. None of the catch clauses match, so none are executed. If none of the enclosing method calls catch the exception, the program terminates.

  46. Answers • No, you catch both exception types in the same way, as you can see from the previous example, since IOExceptionis a checked exception and NumberFormatException is an unchecked exception.

  47. The finally clause • Exception terminates current method • Danger: Program can skip over essential code • Example reader = new FileReader(filename); Scanner in = new Scanner(reader); readData(in); reader.close();// May never get here

  48. The finally clause • Must execute reader.close() even if exception occurs • Use finally clause for code that must be executed "no matter what"

  49. The finally clause FileReader reader = new FileReader(filename); try { Scanner in = new Scanner(reader); readData(in); } finally { reader.close(); } • If an exception occurs, finally clause is also executed before exception is passed to its handler, so file is always closed

  50. The finally clause • Executed when try block is exited in any of 3 ways: • After last statement oftry block • After last statement of catch clause, if this try block caught an exception • When an exception was thrown in try block and not caught • Recommendation: do not mix catch and finallyclauses in same try block • See example in textbook

More Related