COS 260 DAY 26 Tony Gauvin.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
CS102--Object Oriented Programming
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
COMP 121 Week 5: Exceptions and Exception Handling.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Handling errors Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main concepts to be covered.
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Handling errors Writing robust code. 16/12/2004Lecture 10: Handling Errors2 Main concepts to be covered Defensive programming. –Anticipating that things.
CPSC150 Week 13 Chapter 12 Exceptions (from slides provided by textbook web site)
Handling errors Main concepts to be covered Defensive programming. –Anticipating that things could go wrong. Exception handling and throwing. Error.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Handling errors Exception handling and throwing Simple file processing.
Object Oriented Programming
CC1007NI: Further Programming Week 8-9 Dhruba Sen Module Leader (Islington College)
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Objects First With Java A Practical Introduction Using BlueJ Handling errors 1.0.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
Exceptions and Assertions Chapter 15 – CSCI 1302.
1 COS 260 DAY 14 Tony Gauvin. 2 Agenda Questions? 6 th Mini quiz graded  Oct 29 –Chapter 6 Assignment 4 will be posted later Today –First two problems.
OOP (Java): Exceptions/ OOP Objectives – –examine Java's exception handling Semester 2, Exceptions.
Handling errors Main concepts to be covered Defensive programming –Anticipating that things could go wrong Exception handling and throwing Error.
Exceptions in OO Programming Introduction Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Handling errors Main concepts to be covered Defensive programming. –Anticipating that things could go wrong. Exception handling and throwing. Error.
13 Handling errors. 2 Förel. 3Object oriented programming, DAT050, DAI2, 16/17, lp 1 Main concepts to be covered Defensive programming. –Anticipating.
Eighth Lecture Exception Handling in Java
Tirgul 13 Exceptions 1.
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Exceptions The Need for Exceptions Throwing Exceptions
COS 260 DAY 17 Tony Gauvin.
CSE 501N Fall ’09 17: Exception Handling
COS 260 DAY 9 Tony Gauvin.
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Advanced Programming Behnam Hatami Fall 2017.
COS 260 DAY 19 Tony Gauvin.
COS 260 DAY 27 Tony Gauvin.
CSS 161: Fundamentals of Computing
COS 260 DAY 10 Tony Gauvin.
COS 260 DAY 26 Tony Gauvin.
Exception Handling.
COS 260 DAY 18 Tony Gauvin.
CMSC 202 Exceptions 2nd Lecture.
Exceptions 19-Feb-19.
COS 260 DAY 23 Tony Gauvin.
COS 260 DAY 4 Tony Gauvin.
COS 260 DAY 20 Tony Gauvin.
Exceptions 7-Apr-19.
COS 260 DAY 23 Tony Gauvin.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
Exception Handling Contents
Exceptions 10-May-19.
Java Basics Exception Handling.
Exceptions 5-Jul-19.
Exception Handling.
Presentation transcript:

COS 260 DAY 26 Tony Gauvin

Agenda Mini Quiz 10 Assignment 7 not grade yet Assignment 8 Posted Questions? Assignment 7 not grade yet Will be graded this week Assignment 8 Posted Dee Dec 12 Mini Quiz 10 Results Fair (not good…not bad) Capstone progress report 3 Over Due Handling errors

Capstone Project Capstone Project Description Fall 2017.pdf October 2 Proposal Due E-mailed to Tony in Blackboard October 27 Progress Report E-mailed to Tony in Blackboard November 17 Progress Report E-mailed to Tony in Blackboard November 30 Progress Report E-mailed to Tony in Blackboard December 12@8AM All Deliverables & Presentation Due Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Final CountDown Dec 5 Dec 8 Dec 12 @ 8 AM Handling errors Mini quiz 11(last one) Lowest 2 dropped Dec 12 @ 8 AM Assignment 8 due Capstone Projects and presentation Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Objects First with Java Handling errors 6.0 © David J. Barnes and Michael Kölling

Main concepts to be covered Defensive programming. Anticipating that things could go wrong. Exception handling and throwing. Error reporting. Simple file processing. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Typical error situations Incorrect implementation. Does not meet the specification given. Inappropriate object request. E.g., invalid index. Inconsistent or inappropriate object state. E.g. arising through class extension. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Not always programmer error Errors often arise from the environment: Incorrect URL entered. Network interruption. File processing is particular error-prone: Missing files. Lack of appropriate permissions. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Exploring errors Explore error situations through the address-book projects. Two aspects: Error reporting. Error handling. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Address-book-v1g Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Adressbook-book-v1t Ex 14.5 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Defensive programming Client-server interaction. Should a server assume that clients are well-behaved? Or should it assume that clients are potentially hostile? Significant differences in implementation required. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Issues to be addressed How much checking by a server on method calls? How to report errors? How can a client anticipate failure? How should a client deal with failure? © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

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 apportioning blame. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Checking the key Ex 14.8 public void removeDetails(String key) { if(keyInUse(key)) { ContactDetails details = book.get(key); book.remove(details.getName()); book.remove(details.getPhone()); numberOfEntries--; } Ex 14.8 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Server error reporting How to report illegal arguments? To the user? Is there a human user? Can they solve the problem? To the client object? Return a diagnostic value. Throw an exception??? Ex 14.11, 12 & 13 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Returning a diagnostic 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; © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Client can check for success if(contacts.removeDetails("…")) { // Entry successfully removed. // Continue as normal. … } else { // The removal failed. // Attempt a recovery, if possible. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Exception-throwing principles A special language feature. No ‘special’ return value needed. Errors cannot be ignored in the client. The normal flow-of-control is interrupted. Specific client recovery actions are encouraged. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Objects First with Java Throwing an exception /** * 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); The method comment is included to illustrate the @throws javadoc documentation. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Throwing an exception An exception object is constructed: new ExceptionType("...") The exception object is thrown: throw ... Javadoc documentation: @throws ExceptionType reason © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

The exception class hierarchy © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Exception categories Checked exceptions Unchecked exceptions Subclass of Exception Use for anticipated failures. Where recovery may be possible. Unchecked exceptions Subclass of RuntimeException Use for unanticipated failures. Where recovery is unlikely.  Crashed applictation © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

The effect of an exception The throwing method finishes prematurely. No return value is returned. Control does not return to the client’s point of call. So the client cannot carry on regardless. A client may ‘catch’ an exception. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Unchecked exceptions Use of these is ‘unchecked’ by the compiler. Cause program termination if not caught. This is the normal practice. IllegalArgumentException is a typical example. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Argument checking public ContactDetails getDetails(String key) { if(key == null) { throw new IllegalArgumentException( "null key in getDetails"); } if(key.trim().length() == 0) { "Empty key passed to getDetails"); return book.get(key); © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

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."); © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Exception handling Checked exceptions are meant to be caught and responded to. must have “catch” and/or “throws” clauses The compiler ensures that their use is tightly controlled. In both server and client objects. Used properly, failures may be recoverable. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

The throws clause Methods throwing a checked exception must include a throws clause: public void saveToFile(String destinationFile) throws IOException © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

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. } © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

The try statement 1. Exception thrown from here try { addressbook.saveToFile(filename); successful = true; } catch(IOException e) { System.out.println("Unable to save to " + filename); successful = false; 2. Control transfers to here © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Multi-catch try { ... ref.process(); } catch(EOFException | FileNotFoundException e) { // Take action appropriate to both types // of exception. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Polymorphic “catch”ing (incorrect) try{ … some.process(); } catch(Exception e) { doRecovery(); catch (EOFException e) { doFileRecovery(); Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Polymorphic “catch”ing (correct) try{ … some.process(); } catch(EOFException e) { doFileRecovery(); catch (Exception e) { doRecovery(); Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The finally clause 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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

The finally clause A finally clause is executed even if a return statement is executed in the try or catch clauses. A uncaught or propagated exception still exits via the finally clause. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Defining new exceptions Extend RuntimeException for an unchecked or Exception for a checked exception. Define new types to give better diagnostic information. Include reporting and/or recovery information. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

public class NoMatchingDetailsException extends Exception { private String key;   public NoMatchingDetailsException(String key) this.key = key; } public String getKey() return key; public String toString() return "No details matching '" + key + "' were found."; © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Java Assertion Statement Two forms available: assert boolean-expression assert boolean-expression : expression The boolean-expression expresses something that should be true at this point. An AssertionError is thrown if the expression evaluates to false. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

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"; © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Guidelines for Assertions They are not an alternative to throwing exceptions. Use for internal checks. Remove from production code. Don’t include normal functionality: // Incorrect use: assert book.remove(name) != null; © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Error recovery Clients should take note of error notifications. Check return values. Don’t ‘ignore’ exceptions. Include code to attempt recovery. Will often require a loop. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Attempting recovery // Try to save the address book. boolean successful = false; int attempts = 0; do { try { 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; © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Error avoidance Clients can often use server query methods to avoid errors. More robust clients mean servers can be more trusting. Unchecked exceptions can be used. Simplifies client logic. May increase client-server coupling. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Avoiding an exception // 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); The addDetails method could now throw an unchecked exception. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Review Runtime errors arise for many reasons. An inappropriate client call to a server object. A server unable to fulfill a request. Programming error in client and/or server. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Review Runtime errors often lead to program failure. Defensive programming anticipates errors – in both client and server. Exceptions provide a reporting and recovery mechanism. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

File-based input-output Input-output is particularly error-prone because it involves interaction with the external environment. The java.io package supports input-output. java.io.IOException is a checked exception. The java.nio packages. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

File and Path java.io.File provides information about files and folders/directories. java.nio.file.Path is a modern alternative. File is a class; Path is an interface. The Files and Paths (NB: plurals) classes are in java.nio.file. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Readers, writers, streams Readers and writers deal with textual input. Based around the char type. Streams deal with binary data. Based around the byte type. The address-book-io project illustrates textual I/O. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

File output The three stages of file output. Open a file. Write to the file. Close the file. Failure at any point results in an IOException. Use FileWriter for text files. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Text output to file try { FileWriter writer = new FileWriter("name of file"); while(there is more text to write) { ... writer.write(next piece of text); } writer.close(); catch(IOException e) { something went wrong with accessing the file © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Try-with-resource Used for ensuring ‘resources’ are closed after use. Removes need for explicit closure on both successful and failed control flows. Also known as ‘automatic resource management’ (ARM). © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Try-with-resource No close() call required in either clause. 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 No close() call required in either clause. See weblog-analyzer. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Text input from file Use BufferedReader for line-based input. Open a file. Read from the file. Close the file. Failure at any point results in an IOException. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Text input from file BufferedReader created via static newBufferedReader method in the java.nio.file.Files class. Requires a Charset from java.nio.charset, e.g.: "US-ASCII" "ISO-8859-1" © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Text input from file See tech-support-io 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) { See tech-support-io © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Text input from the terminal System.in maps to the terminal: Its type is java.io.InputStream It is often wrapped in a java.util.Scanner. Scanner with File is an alternative to BufferedReader. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Scanner: parsing input Scanner supports parsing of textual input. nextInt, nextLine, etc. Its constructors support String, File and Path arguments. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Review Key classes for text input/output are FileReader, BufferedReader, FileWriter and Scanner. Binary input/output involves Stream classes. The Path interface is an alternative to File. try-with-resource simplifies closing. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.