Topic 4 When Good Programs Go Bad � A variety of errors can occur when a � A E Exceptions and File I/O ti d Fil I/O i t f h program is running. For example: "A slipping gear could let your M203 A slipping gear could let your M203 – (real) user input error. bad url ( l) i t b d l – device errors. remote server unavailable grenade launcher fire when you least – physical limitations. full disk physical limitations full disk expect it. That would make you quite – code errors. interact with code that does not fulfill unpopular in what s left of your unit. unpopular in what's left of your unit " its contact (pre and post conditions) its contact (pre and post conditions) � when an error occurs - THE U.S. Army's PS magazine, August – return to safe state save work exit gracefully return to safe state, save work, exit gracefully 1993, quoted in The Java Programming � error handling code may be far removed Language, 3rd edition from code that caused the error from code that caused the error CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O Java Basics - Exceptions and File I/O 1 2 Computer Science Computer Science How to Handle Errors? Exceptions � It is possible to detect and handle errors of � Many languages, including Java use a various types. mechanism know as Exceptions to handle errors at runtime � Problem: this complicates the code and – In Java Exception is a class with many makes it harder to understand. descendants. – the error detection and error handling code have – ArrayIndexOutOfBoundsException little or nothing to do with the real code is trying to do. – NullPointerException � A tradeoff between ensuring correct behavior – FileNotFoundException under all possible circumstances and clarity – ArithmeticException of the code – IllegalArgumentException CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O 3 Java Basics - Exceptions and File I/O 4 Computer Science Computer Science
Partial Exceptions Hierarchy Creating Exceptions Th Throwable bl � As a program runs, if a situation occurs that is handled by exceptions then an Exception Error Error E ception Exception is thrown. – An Exception object of the proper type is created IOE IOException ti R RuntimeException ti E ti – flow of control is transferred from the current block of code to code that can handle or deal with the exception ith th ti EOFException FileNotFound Exception – the normal flow of the program stops and error handling code takes over (if it exists.) handling code takes o er (if it e ists ) And many, A d many, many Arithmetic NullPointer IndexOut Illegal Exception Exception ofBounds Argument more… more Exception Exception CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O Java Basics - Exceptions and File I/O 5 6 Computer Science Computer Science Attendance Question 1 Unchecked Exceptions Is it possible for the following method to � Exceptions in Java fall into two different categories – checked (other than Runtime) and unchecked (Runtime) result in an exception? � unchecked exceptions are completely preventable and u c ec ed e cept o s a e co p ete y p e e tab e a d // pre: word != null should never occur. public static void printLength(String word){ – They are caused by logic errors, created by us, the programmers. String output = "Word length is " + word.length(); � Descendents of the RuntimeException class � Descendents of the RuntimeException class System.out.println( output ); S t t i tl ( t t ) } � Examples: ArrayIndexOutOfBoundsException, NullPointerException, ArithmeticException A. Yes A. Yes � There does not need to be special error handling code B. No – just regular error prevention code � If error handling code was required programs would be e o a d g code as equ ed p og a s ou d be unwieldy because so many Java statements have the possibility of generating or causing an unchecked Exception CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O 7 Java Basics - Exceptions and File I/O 8 Computer Science Computer Science
Checked Exceptions Required Error Handling Code � If � If you call a method that can generate a � "Ch � "Checked exceptions represent conditions ll th d th t t k d ti t diti that, although exceptional, can reasonably checked exception you must choose how to be expected to occur and if they do occur be expected to occur, and if they do occur deal with that possible error d l ith th t ibl must be dealt with in some way.[other than � For example one class for reading from files is the program terminating.] the program terminating ]" the FileReader class – Java Programming Language third edition public FileReader (String fileName) � Unchecked exceptions are due to a Unchecked exceptions are due to a throws FileNotFoundException programming logic error, our fault and p preventable if coded correctly. y � This constructor has the possibility of throwing a p y g FileNotFoundException � Checked exceptions represent errors that � FileNotFoundException is a checked exception are unpreventable by us! p y CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O Java Basics - Exceptions and File I/O 9 10 Computer Science Computer Science Checked Exceptions in Code Handling Checked Exceptions � If we have code that tries to build a FileReader we � In the code on the previous slide there are in � I th d th i lid th i must deal with the possibility of the exception fact 4 statements that can generate checked import java.io.FileReader; exceptions. exceptions public class Tester { – The FileReader constructor public int countChars(String fileName) { FileReader r = new FileReader(fileName); – the ready method the ready method int total = 0; while( r.ready() ) – the read method { r.read(); total++; – the close method – the close method } r.close(); � To deal with the exceptions we can either return total; } state this method throws an Exception of the state this method throws an Exception of the } } proper type or handle the exception within � The code contains a syntax error. "unreported exception the method itself java.io.FileNotFoundException; must be caught or declared j p ; g to be thrown." CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O 11 Java Basics - Exceptions and File I/O 12 Computer Science Computer Science
Using the throws Keyword Methods that throw Exceptions public int countChars(String fileName) bli i t tCh (St i fil N ) � It may be that we don't know how to deal throws FileNotFoundException, IOException with an error within the method that can { int total = 0; generate it FileReader r = new FileReader(fileName); while( r.ready() ) � In this case we will pass the buck to the { { r read(); r.read(); method that called us total++; } � The keyword throws is used to indicate a y r.close(); l () method has the possibility of generating an return total; exception of the stated type p yp } � Now any method calling ours must also � Now any method calling ours must also throw an exception or handle it throw an exception or handle it throw an exception or handle it throw an exception or handle it CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O Java Basics - Exceptions and File I/O 13 14 Computer Science Computer Science Sample try and catch Blocks Using try-catch Blocks public int countChars(String fileName) { { int total = 0; int total = 0; � If you want to handle the a checked try { FileReader r = new FileReader(fileName); exception locally then use use the keywords while( r.ready() ) { { r.read(); d() try and catch d total++; } � the code that could cause an exception is r.close(); } placed in a block of code preceded by the catch(FileNotFoundException e) { System.out.println("File named " keyword try + fileName + "not found. " + e); ) total = -1; � the code that will handle the exception if it } catch(IOException e) occurs is placed in a block of code preceded p p { { System out println("IOException occured " + System.out.println( IOException occured + "while counting chars. " + e); by the keyword catch total = -1; } return total; return total; } CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O 15 Java Basics - Exceptions and File I/O 16 Computer Science Computer Science
Recommend
More recommend