Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)

Similar presentations

Presentation on theme: "Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)"— Presentation transcript:

1 Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)

2 Input and output with files The Scanner class –reading from –reading from files The PrintWriter class –writing to files The File class

3 Using Scanner to read from Scanner reader = new Scanner(; String str; do{ str = reader.nextLine(); System.out.println(str); } while(str.length()>0);

4 File, Scanner, PrintWriter File inFile = new File(inFileStr); File outFile = new File(outFileStr); Scanner reader = new Scanner(inFile); PrintWriter writer = new PrintWriter(outFile); String str; while(reader.hasNextLine()){ str = reader.nextLine(); System.out.println(str); writer.println(str); } reader.close(); // one of these matters writer.close(); // which one?

5 FileNotFoundException May be thrown by either the Scanner or PrintWriter constructors with a String arg not by the File constructor, because constructing a File object just sets up a way of accessing the file, but does not actually do anything with it Subclass of IOException We have to either catch it or pass it back to the calling method But first…

6 Exceptions When something goes wrong at run-time, the program throws an exception Reason: exceptions cannot be overlooked. Either they are caught (by an exception handler) or the program terminates Some important exceptions in the library –NullPointerException –IllegalArgumentException –IndexOutOfBoundsException –ArithmeticException These methods are called unchecked exceptions. This means that the compiler doesn’t demand that you catch them. However, if they occur, and they are not caught by an exception handler, the program will terminate.

7 Unchecked exceptions - examples An ArithmeticException is thrown if integer division by zero takes place An IndexOutOfBoundsException (actually, the subclass ArrayIndexOutOfBoundsException) is thrown if an attempt is made to access an array element that does not exist (index = length) A NullPointerException is thrown when referencing an object if the reference value is null. Integer.parseInt throws IllegalArgumentException (actually, the subclass NumberFormatException) if its String parameter doesn’t fit the integer format

8 More unchecked exceptions A NegativeArraySizeException is thrown if an attempt is made to construct an array with a negative size The code Object obj = new Rectangle(); String str = (String) obj; throws a ClassCastException (at run time; it compiles fine)

9 Integer overflow is not an exception Unfortunately, integer overflow does not cause an exception to be thrown in Java –int x = (int) 9999999999999.9; –int y = Integer.MAX_VALUE + 1; –int z = (int) Double.MAX_VALUE; The Ariane software bug: an exception was thrown but not handled! Not an issue with float and double, because of inf and nan values

10 We can throw exceptions too Our methods should throw an IllegalArgumentException if called with an argument that is not allowed Example: the Fibonacci methods, when the argument k is negative –throw new IllegalArgumentException(“k must not be negative”); This is important because otherwise method goes into an infinite loop Our methods could throw an IllegalArgumentException if called with an Object reference that is null – but this is not necessary since if we don’t a NullPointerException will probably be thrown We can extend Exception classes by writing subclasses

11 The Throwable class Exception –RunTimeException a much better name would be UncheckedException –ClassNotFoundException –CloneNotSupportedException –AWTException –IOException –others Error (VirtualMachineError, AWTError,…)

12 Checked Exceptions All Exceptions except RunTimeException must be caught using catch If they are not, a compile-time error will occur

13 throw and throws throw is a statement that throws an exception: –if {…} throw new IllegalArgumentException() throws is a keyword that goes at the beginning of a method saying what kinds of exceptions the method may throw –public void method(…) throws IllegalArgumentException { No need to use throws when the method throws an unchecked exception However, any method that may throw a checked exception must declare this with throws

14 Catching an exception A try block calls methods that might throw an exception One or more catch blocks (exception handlers) follow the try block, each one for catching a different exception that might get thrown. We must catch checked exceptions, but we can pass the responsibility further back to the calling method by using throws Catching the FileNotFound exception…

15 Catching unchecked exceptions We don’t have to catch unchecked exceptions (so- called RunTimeExceptions) but we may want to do so Example: using the nextInt method of the Scanner class to read the next int from This may throw an InputMismatchException which is a subclass of RunTimeException so we don’t have to catch it However, by catching it, we can reject it and insist on the user entering an int

16 finally If a try block executes without an exception occurring, execution continues with the next statement following the catch blocks If an exception is caught, the relevant catch block is executed and again control continues with the next statement following the catch blocks Except when? a finally {…} block is used after catch blocks to specify statements that must always executed, no matter what example: close the files

Download ppt "Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)"

Similar presentations

Ads by Google