Topic 4 Exceptions and File I/OWhen Good Programs Go BadHow to Handle Errors?ExceptionsPartial Exceptions HierarchyCreating ExceptionsAttendance Question 1Unchecked ExceptionsChecked ExceptionsRequired Error Handling CodeChecked Exceptions in CodeHandling Checked ExceptionsMethods that throw ExceptionsUsing the throws KeywordUsing try-catch BlocksSample try and catch BlocksMechanics of try and catchGacky try catch BlockMore try catch MechanicsWhat Happens When Exceptions OccurCounting Chars AgainThrowing Exceptions YourselfAttendance Question 2Attendance Question 3Error Handling, Error Handling Everywhere!Error PreventionSlide 27File Input and OutputStreams?StreamsLots of StreamsWorking with Files in JavaThe Scanner classScanner and Keyboard InputHooking a Scanner up to a FileWriting to a FileReading From a Web PageCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O1Topic 4 Exceptions and File I/O"A slipping gear could let your M203 grenade launcher fire when you least expect it. That would make you quite unpopular in what's left of your unit."- THE U.S. Army's PS magazine, August 1993, quoted in The Java Programming Language, 3rd editionCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O2When Good Programs Go BadA variety of errors can occur when a program is running. For example:–(real) user input error. bad url–device errors. remote server unavailable–physical limitations. full disk–code errors. interact with code that does not fulfill its contact (pre and post conditions)when an error occurs–return to safe state, save work, exit gracefullyerror handling code may be far removed from code that caused the errorCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O3How to Handle Errors?It is possible to detect and handle errors of various types.Problem: this complicates the code and makes it harder to understand.–the error detection and error handling code have little or nothing to do with the real code is trying to do.A tradeoff between ensuring correct behavior under all possible circumstances and clarity of the codeCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O4ExceptionsMany languages, including Java use a mechanism know as Exceptions to handle errors at runtime–In Java Exception is a class with many descendants.–ArrayIndexOutOfBoundsException–NullPointerException–FileNotFoundException–ArithmeticException–IllegalArgumentExceptionCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O5Partial Exceptions HierarchyThrowableIOException RuntimeExceptionEOFException FileNotFoundExceptionArithmeticExceptionNullPointerExceptionIndexOutofBoundsExceptionIllegalArgumentExceptionAnd many, many, many more…ErrorExceptionCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O6Creating ExceptionsAs a program runs, if a situation occurs that is handled by exceptions then an Exception is thrown.–An Exception object of the proper type is created–flow of control is transferred from the current block of code to code that can handle or deal with the exception–the normal flow of the program stops and error handling code takes over (if it exists.)CS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O7Attendance Question 1Is it possible for the following method to result in an exception?// pre: word != nullpublic static void printLength(String word){ String output = "Word length is " + word.length(); System.out.println( output );}A. YesB. NoCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O8Unchecked ExceptionsExceptions in Java fall into two different categories–checked (other than Runtime) and unchecked (Runtime)unchecked exceptions are completely preventable and should never occur. –They are caused by logic errors, created by us, the programmers.Descendents of the RuntimeException classExamples: ArrayIndexOutOfBoundsException, NullPointerException, ArithmeticExceptionThere does not need to be special error handling code–just regular error prevention codeIf error handling code was required programs would be unwieldy because so many Java statements have the possibility of generating or causing an unchecked ExceptionCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O9Checked Exceptions"Checked exceptions represent conditions that, although exceptional, can reasonably be expected to occur, and if they do occur must be dealt with in some way.[other than the program terminating.]"–Java Programming Language third editionUnchecked exceptions are due to a programming logic error, our fault and preventable if coded correctly.Checked exceptions represent errors that are unpreventable by us!CS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O10Required Error Handling CodeIf you call a method that can generate a checked exception you must choose how to deal with that possible errorFor example one class for reading from files is the FileReader classpublic FileReader(String fileName) throws FileNotFoundExceptionThis constructor has the possibility of throwing a FileNotFoundExceptionFileNotFoundException is a checked exceptionCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O11Checked Exceptions in CodeIf we have code that tries to build a FileReader we must deal with the possibility of the exceptionThe code contains a syntax error. "unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown."import java.io.FileReader;public class Tester{public int countChars(String fileName){ FileReader r = new FileReader(fileName);int total = 0;while( r.ready() ){ r.read();total++;}r.close();return total;} }CS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O12Handling Checked ExceptionsIn the code on the previous slide there are in fact 4 statements that can generate checked exceptions. –The FileReader constructor–the ready method–the read method–the close methodTo deal with the exceptions we can either state this method throws an Exception of the proper type or handle the exception within the method itselfCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O13Methods that throw ExceptionsIt may be that we don't know how to deal with an error within the
View Full Document