Presentation is loading. Please wait.

Presentation is loading. Please wait.

Handling errors 5.0. 2 Main concepts to be covered Defensive programming –Anticipating that things could go wrong Exception handling and throwing Error.

Similar presentations


Presentation on theme: "Handling errors 5.0. 2 Main concepts to be covered Defensive programming –Anticipating that things could go wrong Exception handling and throwing Error."— Presentation transcript:

1 Handling errors 5.0

2 2 Main concepts to be covered Defensive programming –Anticipating that things could go wrong Exception handling and throwing Error reporting Simple file processing Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

3 3 Typical error situations Incorrect implementation –does not meet the specification –e.g. mean vs. median value Inappropriate object request –e.g. invalid index Inconsistent or inappropriate object state –e.g. arising through class extension Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

4 4 Not always programmer error Errors often arise from the environment: –Incorrect URL entered –Network interruption File processing is particularly error- prone: –Missing files –Lack of appropriate permissions Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

5 5 Exploring errors Explore error situations through the address-book projects Two aspects: –Error reporting –Error handling Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

6 6 Defensive programming Client-server interaction –Server: (AddressBook) initiates NO actions –Client: requests activities from server Views when implementing server class –Should a server assume that clients are well-behaved with sensible requests? –Or, assume that clients are potentially hostile with problematic requests? Significant differences in implementation Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

7 7 Issues to be addressed How much checking by a server on method calls accessed by a client? How should a server report errors to its clients? How can a client anticipate failure of a request to a server? How should a client deal with failure? Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

8 8 An example Create an AddressBook object Try to remove an entry A runtime error results –Whose ‘fault’ is this? Anticipation and prevention are preferable to assigning blame Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

9 9 Argument values Arguments represent a major ‘vulnerability’ for a server object –Constructor arguments initialize state –Method arguments often contribute to behavior Argument checking is one defensive measure Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

10 10 What could go wrong? Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public void removeDetails(String key) { ContactDetails details = book.get(key); book.remove(details.getName()); book.remove(details.getPhone()); numberOfEntries--; }

11 11 What could go wrong? Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public void removeDetails(String key) { ContactDetails details = book.get(key); book.remove(details.getName()); book.remove(details.getPhone()); numberOfEntries--; }  Assumes key passed to it is a VALID key in book  What is the value of details if book is empty?  What is the value of details if the key is not found?  What happens when book.remove is invoked?

12 12 Parameter checking Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public void removeDetails(String key) { if(keyInUse(key)) { ContactDetails details = book.get(key); book.remove(details.getName()); book.remove(details.getPhone()); numberOfEntries--; } Server object most vulnerable receiving external values Passed values directly influence the overall effect/result Vital for server to know whether to TRUST or CHECK any parameter values that it receives Neither ContactDetails nor AddressBook classes check Thus, checking is done here in the server relatively easily

13 13 Server error reporting How to report illegal arguments? –To the end user via display device? Is there a visual display device? Is there a human user? Can they really solve the problem? Inappropriate messages may annoy the user –To the programmer via server object? Return a diagnostic value o boolean ( i.e. true or false ) o integer ( i.e. OUT_OF_BOUNDS == -1 ) o object ( i.e. null ) Throw an exception o prevents client programmer from ignoring the consequences of method failure Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

14 14 Server returns a diagnostic Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public boolean removeDetails(String key) { if(keyInUse(key)) { ContactDetails details = book.get(key); book.remove(details.getName()); book.remove(details.getPhone()); numberOfEntries--; return true; } else { return false; } Non-void return indicating either success or failure

15 15 Client can check for success Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling if(contacts.removeDetails("…")) { // Entry successfully removed. // Continue as normal. … } else { // The removal failed. // Attempt a recovery, if possible. … } Non-void return indicating either success or failure

16 16 Potential client responses Test the return value –Attempt recovery on error –Avoid program failure Ignore the return value –Cannot be prevented –Likely to lead to program failure Exceptions are preferable Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

17 17 Exception-throwing principles A special language feature No special return value needed –May be used regardless of return type Errors can not be ignored in the client –The normal flow-of-control is interrupted –Application terminates if failure ignored Specific recovery actions are encouraged –Error discovery in the server’s method –Recovery attempted in the client Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

18 18 Throwing an exception Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling /** * Look up a name or phone number and return the * corresponding contact details. * @param key The name or number to be looked up. * @return The details corresponding to the key, * or null if there are none matching. * @throws IllegalArgumentException * if the key is invalid. */ public ContactDetails getDetails(String key) { if(key == null) { throw new IllegalArgumentException( "null key in getDetails"); } return book.get(key); }

19 19 Throwing an exception An exception object is constructed: – new ExceptionType("...") –diagnostic string passed to constructor o available to exception receiver using getMessage & toString methods The exception object is thrown: – throw... –unhandled exceptions result in o diagnostic string shown to user o termination of program Javadoc documentation tag: – @throws ExceptionType reason Exception object represents the details of a program failure.

20 20 The exception class hierarchy Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling IllegalArgumentException used regularly to indicate inappropriate actual parameter value passed java.lang runtime-system errors user-controllable errors

21 21 Exception categories Unchecked exceptions –Subclass of RuntimeException –For unanticipated failures i.e. retrieve non-existing position –Where recovery is unlikely Checked exceptions –Subclass of Exception –For anticipated failures i.e. write to full disk –Where recovery may be possible

22 22 Which exception to throw? UNCHECKED –Situations that should lead to program failure o assumes error prevents program continuation –Situations that could be reasonably avoided o such as calling a method on a null variable CHECKED –Situations with possibility of client recovery o assumes server is aware of context for client recovery –Situations beyond programmer control o such full disk or network connection drop

23 23 The effect of an exception Throwing method finishes prematurely No return value is returned or required Control does not return to the client’s point of call –So the client cannot carry on regardless A client may catch an exception But an uncaught exception results in termination with exception indication Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

24 24 Unchecked exceptions Use of these is unchecked by the compiler –Not in method where exception is thrown –Not client where method is called Cause program termination if not caught –This is the normal practice IllegalArgumentException is typical –Indicating passed parameter value is invalid Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

25 25 Argument checking Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public ContactDetails getDetails(String key) { if(key == null) { throw new IllegalArgumentException( "null key in getDetails"); } if(key.trim().length() == 0) { throw new IllegalArgumentException( "Empty key passed to getDetails"); } return book.get(key); // return only if passed key } // is not null or empty Worth checking for an illegal parameter value BEFORE continuing on with method purpose to ensure that a partial mutation does NOT leave an inconsistent state!!

26 26 Preventing object creation Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Use exceptions to prevent objects from being creating in an invalid initial state –Possible inappropriate parameter value passed –Throw exception in constructor same as method Constructor should include checks –Fail to create object with invalid parameters –Throw IllegalStateException –Same effect on the client as if method thrown

27 27 Preventing object creation public ContactDetails(String name, String phone, String address) { if(name == null) { name = ""; } if(phone == null) { phone = ""; } if(address == null) { address = ""; } this.name = name.trim(); this.phone = phone.trim(); this.address = address.trim(); if(this.name.length() == 0 && this.phone.length() == 0) { throw new IllegalStateException( "Either the name or phone must not be blank."); } BOTH name and phone can NOT be null

28 28 Exception handling Checked exceptions are meant to be caught and responded to –from the Exception subclass –not RuntimeException (unchecked) The compiler ensures that their use is tightly controlled –In both server and client objects Used properly, failures may be recoverable –In both server and client objects Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

29 29 The throws clause Methods throwing a checked exception (but not when its a runtime exception) must include a throws clause in the header: public void saveToFile(String destinationFile) throws IOException Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling saveToFile method throwing exception MUST declare that it does so in its header!! Unchecked exceptions may also throws clause … but it is NOT required and NOT recommended!!

30 30 The try statement Clients catching an exception MUST protect the call with a try statement: try { Protect one or more statements here. } catch(Exception e) { Report and recover from the exception here. } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Exception handler marked by a try and catch: reporting and/or recovery Variable e used to refer to the exception object to provide information to support recovery & reporting

31 31 The try statement Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling try { addressbook.saveToFile(filename); successful = true; } catch(IOException e) { System.out.println("Unable to save to " + filename); successful = false; } 1. Exception thrown from here 2. Control transfers to here Possible failures Recover & report If no exception arises during execution of protected statements in the try block, then the catch block will be skipped!!

32 32 Catching multiple exceptions try {... ref.process();... } catch(EOFException e) { // Take action on an end-of-file exception... } catch(FileNotFoundException e) { // Take action on a file-not-found exception... } public void process() throws EOFException, FileNotFoundException All CHECKED exceptions must be listed in the throws clause of the method Multiple catch blocks for all exceptions … compared in sequence and only the first matching exception type’s catch block is executed

33 33 Multi-catch – a Java 7 feature Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling try {... ref.process();... } catch(EOFException | FileNotFoundException e) { // Take action appropriate to both types // of exception.... } Allows multiple exceptions to be handled in the same catch block and also reduces code duplication

34 34 Propagating an exception Exception may be propagated from client method to its caller … and possibly beyond Method is propagated simply by NOT including an exception handler However, checked exceptions require a throws clause –Even if it does not create and throw exception –Method with throws in header, but no throw statement in the method body Common when calling method unable to recover –Or method does not need to recover –Or constructors may not be able to recover from failing to set up a new object

35 35 The finally clause Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling try { Protect one or more statements here. } catch(Exception e) { Report and recover from the exception here. } finally { Perform any actions here common to whether or not an exception is thrown. } Optional clause executed whether an exception occurs or not; either at the end of the try block (with no exceptions) … OR after appropriate catch block is executed (if exception thrown)

36 36 The finally clause A finally clause is executed even if a return statement is executed in the try or catch clauses The finally clause is still executed if an exception is thrown but not caught –An uncaught, unchecked exception –A propagated checked exception, handled at a higher level in call sequence Possible to omit catch blocks if all exceptions are propagated –Using try block and finally clause Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

37 37 Defining new exceptions Unchecked exceptions –extend RuntimeException Checked exceptions –extend Exception Define new types to give better diagnostic information –Include reporting and/or recovery information Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

38 38 public class NoMatchingDetailsException extends Exception {// checked exception private String key; public NoMatchingDetailsException(String key) {// formal parameters this.key = key; } public String getKey()// accessor method for {// key with details return key; } public String toString()// overridden method for {// diagnostic string return "No details matching '" + key + "' were found."; } address-book example

39 39 Assertions Used for internal consistency checks –e.g. object state following mutation Used during development and normally removed in production version –e.g. via a compile-time option Java has an assert statement Similar to that in Junit testing Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

40 40 Java Assertion Statement Two forms available 1. assert boolean-expression 2. assert boolean-expression : expression boolean-expression expresses something that should be true at this point –true: no further effect of assert –false: AssertionError is throw (optional) expression in alternate form –expression value turned into a String –passed to AssertionError constructor to provide a diagnostic string

41 41 Assert Statement public void removeDetails(String key) { if(key == null){ throw new IllegalArgumentException("..."); } if(keyInUse(key)) { ContactDetails details = book.get(key); book.remove(details.getName()); book.remove(details.getPhone()); numberOfEntries--; } assert !keyInUse(key); assert consistentSize() : "Inconsistent book size in removeDetails"; } 1.Assumes key was not or is now no longer in use 2.Assumes the numberOfEntries field accurately represents the current number of unique details

42 42 Guidelines for Assertions Intended to perform consistency checks NOT alternative to throwing exceptions Used for internal checking during development and testing Only if requested, compiled into code But remove from production code Don’t include normal functionality: // Incorrect use … // to combine assertion with removal assert book.remove(name) != null;

43 43 Error recovery Clients should take note of error notifications –Check return values –Do not ignore exceptions –Should not carry on regardless Include code to anticipate and recover from errors requires a complex flow of control –Thrown exception in try block supplies the error- recovery mechanism –catch block sets up the recovery –Important to repeat attempts to correct o Place try in a loop o Prevent endless unsuccessful attempts ( MAX_ATTEMPTS ) –Successful recovery can not be guaranteed

44 44 Attempting recovery // Try to save the address book. boolean successful = false; int attempts = 0; do {// repeated attempts with alternate try {// filenames until contacts.saveToFile(filename); successful = true; } catch(IOException e) { System.out.println("Unable to save to " + filename); attempts++; if(attempts < MAX_ATTEMPTS) { filename = an alternative file name ; } } while(!successful && attempts < MAX_ATTEMPTS); if(!successful) { Report the problem and give up; } Repeated attempts with alternate filenames (from a list or user input) until successful or a certain number of attempts completed.

45 45 Error avoidance Thrown exception may result in: –Worst … fatal termination of program –Best … messy to recover from in client –Easier to avoid errors in the first place!! Clients can often use server query methods to avoid errors ( i.e. keyInUse) –More robust clients = more trusting servers –Unchecked exceptions can be used –Simplifies client logic May increase client-server coupling –Server check-methods are visible to client –Or, server and client code duplication

46 46 Avoiding an exception Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling // Use the correct method to put details // in the contacts list. if(contacts.keyInUse(details.getName() || contacts.keyInUse(details.getPhone()) { contacts.changeDetails(details); } else { contacts.addDetails(details); } By completely avoiding a DuplicateKeyException, the addDetails method could now be downgraded to throw an unchecked exception.

47 47 Review Runtime errors arise for many reasons –Inappropriate client call to server object –A server unable to fulfill a request –Programming error in client and/or server Runtime errors often lead to program failure Defensive programming anticipates errors – in both client and server Exceptions provide a reporting and recovery mechanism

48 48 File-based input-output Input-output is particularly error-prone with external environment interaction java.io package supports input-output –Core package that is platform-independent –Checked exception java.io.IOException o General indicator that something went wrong o Almost any i/o operation must anticipate this  Subclasses FileNotFoundException or EOFException Java 7 adds shift to java.nio packages

49 49 File and Path java.io.File provides information about files and folders/directories –Independent of file system ( i.e. OS ) –Name of file passed to File constructor –Creating File object does not create file –Results in file details stored in File object o exists, canRead, canWrite, getParent, isDirectory, etc… o not much to determine file contents thru File object Java 7 java.nio.file.Path alternative –Path interface creates concrete instance via static get method of Paths class –Equivalent Path object from File via toPath File is a class - Path is an interface Files & Paths in java.nio.file also used –Files class provides static methods o exists, isReadable, isDirectory, isWritable, etc… o probeContentType attempts information on file contents

50 50 Readers, writers, streams Text files –i.e. HTML web pages, human-readable text –Based around char type –Processed using readers and writers Binary files –i.e. images, executables, word processors –Based around byte type –Processed using stream heandlers address-book-io illustrates textual I/O Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

51 51 File output The three stages of file output –Open a file –Write to the file –Close the file (but see ARM in Java 7) Failure at any point results in IOException Text file writing, create FileWriter object –file parameter in form of String or File object –Open external file & prepare it to receive output o Failure to open results in IOException thrown o Successful open allows write to store char strings in file o Attempts to write could still fail, although rare After all output written, close the file –Ensures all data written to external file –Frees up internal-external resources o Attempts to write could still fail, although rare

52 52 Basic pattern Text output to file try { // 1. open file FileWriter writer = new FileWriter("name of file"); while( there is more text to write ) {... writer.write( next piece of text ); // 2. write data... } writer.close(); // 3. close file } catch(IOException e) { something went wrong with accessing the file } See the weblog-analyzer project Exception handling during file: Opening – repeat with alternate filenames Writing – unlikely repeated attempts will succeed Closing – not usually worth a further attempt If failure occurs after file is opened, it is left open and wastes program resource!!

53 53 Try-with-resource Java 7 Used for ensuring resources are closed after use –Whether use was successful or not Removes need for explicit closure on both successful and failed control flows Also known as … ARM … automatic resource management Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

54 54 Try-with-resource Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling try(FileWriter writer = new FileWriter("name of file")) { while( there is more text to write ) {... writer.write( next piece of text );... } catch(IOException e) { something went wrong with accessing the file } Resource created as parameter for try and resulting in close() being called automatically after try statement, thus NO close() call required in either clause body Only appropriate for classes implementing I/O AutoCloseable interface

55 55 Text input from file Basic pattern for input is same as output –Open a file –Read from the file –Close the file (but see ARM in Java 7) Use the FileReader class –Ability to read a single character –BUT not a line (no predetermined length) Line-based input using BufferedReader –readLine method to read a line –BUT can not open files –Use FileReader wrapped in BufferedReader Any failure results in an IOException

56 56 Text input from file try { BufferedReader reader = // wrap during creation new BufferedReader(new FileReader("filename")); String line = reader.readLine(); while(line != null) { do something with line line = reader.readLine(); } reader.close(); } catch(FileNotFoundException e) { the specified file could not be found } catch(IOException e) { something went wrong with reading or closing } readLine removes line-termination character from String and returns a null value to indicate end of file

57 57 Text input from file Java 7 alternative BufferedReader created via static newBufferedReader method in the java.nio.file.Files class Requires Path parameter for file Also requires a Charset from java.nio.charset to describe the set of characters in the file: –"US-ASCII" –"ISO-8859-1" Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

58 58 Text input Java 7 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Charset charset = Charset.forName("US-ASCII"); Path path = Paths.get("file"); try(BufferedReader reader = Files.newBufferedReader(path, charset)) { use reader to process the file } catch(FileNotFoundException e) { deal with the exception } catch(IOException e) { deal with the exception } Normal way of creating a BufferedReader via static newBufferedReader method of the Files class … in Java 7

59 59 Scanner: parsing input BufferedReader treats input as unstructured Some text files stored as multi-typed data values –e.g. comma-separated values (CSV) format o Multiple values separated by comma (or other char) –Implicit structure may be identified by parsing –Piecing individual characters into values is scanning Scanner supports parsing of textual input –nextInt, nextLine, etc. –Scans text and converts to typed values ( e.g. int) –Often used directly instead of BufferedReader Constructor supports String, File and (in Java 7) Path arguments Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

60 60 Scanner May not be guaranteed to read the entire file –hasNextInt may return false if text unrecognizable as an integer o Data gathering will then be terminated Possible to mix calls to different next methods –Data contained may be of mixed types Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

61 61 Text via terminal System.out ( e.g. calls to print and println ) –Maps to standard output terminal –Type is java.io.PrintStream System.in ( corresponding source for input ) –Maps to standard input terminal –Type is java.io.InputStream –Limited with input one character at a time System.in wrapped in a Scanner Scanner reader = new Scanner(System.in); … intervening code omitted … String inputLine = reader.nextLine(); nextLine returns next complete line from standard input ( without the final \n character )

62 62 newline - text file output Escape sequences are 2 or more characters (starting with a “\”) which translate into another harder-to- represent character(s) such as a control-character: \n line-feed(LF) character ('\u000A') vertically advances one line down \r carriage-return(CR) character ('\u000D') horizontally to the beginning of the line newline character for text output is platform-specific: DOS/Windows \r\n UNIX \n MacOS(older) \r MacOS(newer) \n

63 63 Object serialization Writes whole object to an external file –Single write operation –Read back later using single read operation Simple objects and multi-component objects Reliable process to restore exact object state Must implement Serializable interface –As defined in java.io –Interface contains NO methods –Managed automatically by runtime system –Requires little user-defined code

64 64 Review Input/output is an area where errors cannot be avoided The environment in which a program is run is often outside a programmer’s control Exceptions are typically checked Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

65 65 Review Key classes for text input/output are FileReader, BufferedReader, FileWriter and Scanner Binary input/output involves Stream classes Java 7 introduces the Path interface as an alternative to File Java 7 introduces try-with-resource Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling


Download ppt "Handling errors 5.0. 2 Main concepts to be covered Defensive programming –Anticipating that things could go wrong Exception handling and throwing Error."

Similar presentations


Ads by Google