Upload
marion-howard
View
215
Download
0
Embed Size (px)
Citation preview
CS61B L10 Exceptions (1) Garcia / Yelick Fall 2003 © UCB
2003-09-17 Dan Garcia
(www.cs.berkeley.edu/~ddgarcia)
Kathy Yelick (www.cs.berkeley.edu/~yelick)
inst.eecs.berkeley.edu/~cs61b/www.ucwise.org1 Handout: notes
Computer Science 61BData Structures and Advanced Programming
Lecture 10 – Exceptions
CS61B L10 Exceptions (2) Garcia / Yelick Fall 2003 © UCB
Change which lines to protect invariant?
1: none 2: 2 3: 2&34: 2&45: 3&46: 2-47: 2-5
1) public class Landlord {2) public Vector myPlots; 3) Landlord (Vector initP) {
myPlots = initP; }4) Vector getPlots () {
return myPlots; }5) Plot plotAt(int i) {
return myPlots.get(i); }6) }
0
5
10
15
20
none 2 2&3 2&4 3&4 2-4 2-5
Nu
mb
er o
f re
spo
nse
s HighCL
MediumCL
LowCL
// invariant: Plots do not overlap
CS61B L10 Exceptions (3) Garcia / Yelick Fall 2003 © UCB
Users’ variables
Which Variables Are Problems?
ownermyPlots
myStart
mySize
myStart
mySize
internalVec
internalPlot
internalVec is a problem, internalPlot is not
… …
CS61B L10 Exceptions (4) Garcia / Yelick Fall 2003 © UCB
Representation Exposure• A well-designed data abstraction can
guarantee its representation invariants– Variables are usually private to ensure invariants
• User may still be able to violate the invariants– Representation exposure: giving the user of an
abstract data type access to the internals, allowing them to violate representation invariants
• If all fields are private, how does this happen?– Taking mutable objects from user and putting
them into the internal state– Returning mutable parts of the state
CS61B L10 Exceptions (5) Garcia / Yelick Fall 2003 © UCB
Abstraction Functions• Given any legal concrete object, what is its
abstract value?– A concrete object is the set of internal variables
» The below-the-line view– The abstract value is in the programmer’s mind
» The above-the-line view» e.g., a Fraction is a rational number, int1/int2
– A concrete object is legal if the representation invariant holds, I.e., repOk is true
• This object represents the rational number ½ :
• So does this one:1
myNumer
2 myDenom
4 myNumer
8 myDenom
1
2
CS61B L10 Exceptions (6) Garcia / Yelick Fall 2003 © UCB
Abstraction Functions• Abstraction functions map concrete to abstract
values (below to above the line)– They are often many-to-one, because several
concrete states may represent the same abstract object
• Liskov talks about abstraction functions as a documentation idea, but notation is difficult
• Instead, we will use the toString method as the abstraction function – The toString result is the abstract value
• The different implementations of Fraction have different toString methods:– If stored in lowest form, then toString is one-to-one– If not, toString is many-to-one
CS61B L10 Exceptions (7) Garcia / Yelick Fall 2003 © UCB
What Makes a Good toString?•Design toString carefully; it should:
1.Distinguish between all distinct abstract values»If 2 objects are not .equals, their toString should not be
2.Not reveal internal information»If 2 objects are .equals, their toString should be
•Sometimes #1 is becomes too cumbersome:– A Landlord is shown: ---DD--KKK--D-----
if Dan, Kathy, and David have all rented plots
•#2 means: don’t reveal redundant information– A linked list with a tail pointer or a size field– Information added to speed up operations
CS61B L10 Exceptions (8) Garcia / Yelick Fall 2003 © UCB
Data Abstraction Summary• Data Abstraction is a powerful programming
tool– Hide the implementation details– Allow for future changes (better/faster…)
• Representation Invariant– Rules about how the internal variables are managed– repOk() checks whether rules have been violated
• Abstraction Function– Maps concrete representation to the abstract value– toString() typically defines this function
• Benevolent side effects– Modifications of internal state that are not
externally visible
CS61B L10 Exceptions (9) Garcia / Yelick Fall 2003 © UCB
What to do with Erroneous Input
• In mathematics, two kinds of functions:– Total function is one that is defined everywhere– Partial function is only defined on some values
• Same applied to programs– Methods are total if the spec has no @requires – Methods are partial if they do: behavior is not
defined when must condition is not met• Methods that are only partial are harder to
use:– But what to do about “bad” input?
» Creating a bank account with a negative balance» Reading from a file, which is suddenly deleted
– Change the spec to define a particular behavior for every input, but was is the right behavior?
CS61B L10 Exceptions (10) Garcia / Yelick Fall 2003 © UCB
Approaches to Handling Bad Inputs
• What to do about this (rare) kind of “exceptional” behavior?– Have every method take an extra parameter,
which will be mutated if there is an exception
– Have every method return a status, e.g., 0 for normal, nonzero if some exception occurred
•What about methods that already return values? public IslamicDate tomorrow() •Return an object containing the normal value + status?
•Need to define a new class (Yuck!)
•Can we add an extra int argument for status? public IslamicDate tomorrow (int status) •No: need to pass in a mutable status object (Yuck!)
CS61B L10 Exceptions (11) Garcia / Yelick Fall 2003 © UCB
Java’s Approach to Exceptions• Java allows you to write a method that either
– Returns a normal value – Or returns a special “Exception” object
• A throw statement says to throw the Exception. if (input == null) { throw new IllegalArgumentException (“null input”); }
• Throwing an exception is like “return”:– The method exits it should be inside a
conditional or at the end of a method – nothing after it will run.
– It will send back the given Exception object
CS61B L10 Exceptions (12) Garcia / Yelick Fall 2003 © UCB
What are Exceptions?• Exceptions are objects
– Exceptions have methods, like getMessage()– The can be passed around and stored– They can be created using a constructor new Exception (“That was bad input”)– Are instance of Exception class, or some other
class that is a subtype of Exception» Seen in the java API in the list at the top» More on this later
• They have special behavior:– Can throw and catch exceptions
Object
Exception ...Integer
CS61B L10 Exceptions (13) Garcia / Yelick Fall 2003 © UCB
When an Exception is Thrown•Example of a Java method that doesn’t always workpublic static int readInt(BufferedReader br){ String input = br.readLine(); return Integer.parseInt(input);}
•Problem: readLine will fail sometimes if there are I/O problems, e.g., the file you are reading from is removed
•The specification for readLine says:
public String readLine()throws IOException
…stuff omitted
Throws: IOException - If an I/O error occurs
•A method that calls readLine must handle the exception
CS61B L10 Exceptions (14) Garcia / Yelick Fall 2003 © UCB
Handling Exceptions: Approach 1
•Handle the exception in the callerpublic static int readInt(BufferedReader br) { try { String input = br.readLine(); return Integer.parseInt(input); } catch (IOException ioe) { System.err.println(“Unable to read int, ” + “defaulting to 0”); return 0; }}
•No change to signature, but changes the internals
•Right approach if the problem can be fixed– The above example is dubious style, defaulting to 0
CS61B L10 Exceptions (15) Garcia / Yelick Fall 2003 © UCB
Exception Handling in General• General format for try/catch:
try { Statements0} catch (ExceptionName1 var1) { Statements1 } Statements2
• Two possible executions:1. Execute Statements0. If no exception occurs, skip
catch and Statements1 and continue with Statement2
2. Start executing Statements0. If an exception occurs, stop in the middle of Statement0 (wherever you are), and jump to Statements1. Then go to Statements2.
Declares name for exception object
var1 can be used inside Statements1, e.g., var1.getMessage()
CS61B L10 Exceptions (16) Garcia / Yelick Fall 2003 © UCB
Handling Exceptions: Approach 2
• The second approach is to “pass the buck”• Re-throw the exception from this method
public static int readInt1(BufferedReader br) throws IOException {
String input = br.readLine();
return Integer.parseInt(input);
}
• This changes the signature and is the right approach if– The exception makes sense to callers of the method– Problem cannot be fixed within this method
CS61B L10 Exceptions (17) Garcia / Yelick Fall 2003 © UCB
Throws vs. Throw• A throws clause in a method signature says:
1. This method may throw the listed Exceptions
2. If any called procedures within throws them, they will be passed along
public static int readInt1(BufferedReader br) throws IOException { ... }
• A throw statement says to actually throw thethrow new IOException(“No file”);
CS61B L10 Exceptions (18) Garcia / Yelick Fall 2003 © UCB
Two Kinds of Exceptions• All Exception types (named …Exception by
convention) are subtypes of Exception• 2 Kinds:
“checked” exceptions
“unchecked”
exceptions
Object
Exception
RuntimeException
IllegalArgumentException
NullPointerException
IndexOutOfBoundsException(many others not shown)
IOException
(many others not shown)
1. Unchecked exceptions are subtypes of RuntimeException
2. Checked exceptions are everything else
CS61B L10 Exceptions (19) Garcia / Yelick Fall 2003 © UCB
Exceptions• When writing a method that throws an
Exception:– Checked: Java requires throws in method signature – Unchecked (RuntimeException): Throws in method
signature is allowed but not required
• When calling a method that throws an Exception:– Checked: Java requires either:
» try/catch around method call» throws in method signature
– Unchecked Exceptions do not require these.
• A “catch” clause with an exception type will catch any subtype, e.g, try {…} catch (Exception e) { }– This is very dangerous, why?
CS61B L10 Exceptions (20) Garcia / Yelick Fall 2003 © UCB
PRS Question•Given the Account class with the deposit
method below, what will the the last line print?
1: 50 2: -950 3: Undef: behavior not specified
4: Compiler err5: Runtime err
public deposit (int amt) { int tmpBal = myBalance; myBalance -= amt; if (myBalance < 0) { throw new IllegalArgumentException(); myBalance = tmpBal; }} // remaining code outside in mainkathy = new Account(50);kathy.deposit(-1000);System.out.println(kathy.balance());
CS61B L10 Exceptions (21) Garcia / Yelick Fall 2003 © UCB
Announcements - Quiz• Open book/open notes• Topics:
– Basic Java
1. Writing and using classes and methods
2. Conditionals, loops, and recursion
3. Parameter passing
4. Primitive values vs. objects (and references to them)
5. public and private
6. static and non-static (hw3)
7. Using Exceptions (lab 4)
8. Vectors/Enumerations (lab 4)
Note: repOK and loop invariants will not be on this exam– Specifications (@param, @return, @requires, modifies”)– Testing (lab 3, not specific test framework in next lecture)
CS61B L10 Exceptions (22) Garcia / Yelick Fall 2003 © UCB
Announcements - Quiz• Review session
– Tuesday or Wednesday evening: watch newsgroup for details
• Exam questions often use examples you have seen. – We will include the code, but you will have time problems if
you’re seeing it for the first time.
• Examples from labs and homeworks (through lab 4 and homework 3):– Account (lab)– Fraction (lecture)– StringFormat (hw)– StringCheck (lab)– IslamicDate (hw2)– Vector and Enumeration (lab)
• Solutions for labs and homeworks online