Felix Grund
Instructor @ UBC
// REQUIRES: numItems > 0
// MODIFIES: this
// EFFECTS: adds numItems to quantity of
// items purchased on this line item
public void addQuantity(int numItems) {
this.quantity += numItems;
}
Let's break this!!
lineItem.addQuantity(-1);
Dear User - we have found that you passed in a
negative number to our addQuantity method.
This is not supported. We kindly ask you to
enter a positive number.
Method is not robust: requires clause excludes values
// MODIFIES: this
// EFFECTS: adds numItems to quantity of
// items purchased on this line item
// IF numItems < 1
// throws IllegalNumberException
public void addQuantity(int numItems)
throws IllegalNumberException {
if (numItems < 1) {
throw new IllegalNumberException();
}
this.quantity += numItems;
}
Method is robust: specifies behaviour for ALL inputs
public class IllegalNumberException extends Exception {
}
catch?
catch?
catch?
LineItem
addQuantity
GroceryBill
addPurchase
GroceryApp
main
catch?
catch?
public void addPurchase(GroceryItem item, int quantity) {
// ...
try {
entry.addQuantity(quantity);
} catch (IllegalNumberException e) {
System.err.println("Quantity could not be added: " + quantity);
}
// ...
}
LineItem
addQuantity
GroceryBill
addPurchase
GroceryApp
main
public void addPurchase(GroceryItem item, int quantity) {
// ...
try {
entry.addQuantity(quantity);
} catch (IllegalNumberException e) {
System.err.println("Quantity could not be added: " + quantity);
} finally {
System.out.println("Your quantity might have been added. Not sure.");
}
// ...
}
public void writeStringToFile(String string) {
FileWriter fw = new FileWriter("OutputFile.txt")
PrintWriter pw = new PrintWriter(fw);
try {
pw.println(string);
} catch (IOException e) {
System.out.println("Could not write to file");
} finally {
pw.close();
}
}
Extra: Git branches
Branch: main
Branch: mybranch
Create
Branch
Merge
Branch
Commits
Lecture Ticket
public void addPurchase(GroceryItem item, int quantity)
throws CouldNotAddPurchaseException {
// ...
try {
entry.addQuantity(quantity);
} catch (IllegalNumberException e) {
System.err.println("Quantity could not be added: " + quantity);
throw new CouldNotAddPurchaseException();
} // POSSIBLY MORE CATCH CLAUSES TO CATCH OTHER EXCEPTIONS
// ...
}
GroceryBill bill = new GroceryBill();
try {
bill.addPurchase(milk, 2);
} catch (CouldNotAddPurchaseException e) {
System.err.println("At least one purchase could not be added");
}
By Felix Grund