Untitled
COMP5017: Data Structures and Algorithms
Assertions and Exceptions
Assertions
Definition: An assertion is a statement that something should be true at a specific point in a program.
Syntax:
assert boolExp;assert boolExp : message;Where
boolExpis a Boolean expression andmessageis a string that describes the assertion's failure.Equivalent sematic:
java if (boolExp) ; // do nothing – all is well else quit program and display message
Purpose: Assertions document assumptions about the program, check for valid assumptions, and signal logic errors clearly to developers.
Preconditions and Postconditions
Example Method: getAverage
public static double getAverage(ArrayList<Integer> numbers) {
int sum = 0;
for (int n: numbers) {
sum += n;
}
return (double)sum / (double)numbers.size();
}
Preconditions: Conditions that must be satisfied before the method is executed.
Sensible preconditions for
getAverage:numbersnot nullnumbers.size() > 0
Postcondition: The condition that must be satisfied after the method has executed.
Good Postcondition for
getAverage:average * numbers.size() ≈ sum
Reasoning Against Error Values:
Returning an error value like -1 could conflict with valid data (e.g., average of negative integers).
Writing to standard error lacks context; it may not be seen by the calling methodology.
Sensible Handling of Violated Preconditions:
Options include halting the program or throwing an exception.
Assertions in Process
Placement:
Recommended to favour single-entry single-exit styles to avoid early returns that hinder assertion checks.
Example implementation of assertions within
getAverage:
assert numbers != null : "List is null";
assert numbers.size() > 0: "List is empty";
Tolerance Level in Assertions:
Example tolerance check for average calculation:
assert Math.abs(average * numbers.size() - sum) < tolerance : "Wrong!";
Java Assertion Checking:
Enabled by default in Codio, no action required.
In NetBeans:
Right-click project > Properties > Run > Enter
-eaor-enableassertionsin VM Options.In IntelliJ:
Choose Run → Edit Configurations, select desired configuration, and add
-eato VM options.
Design by Contract
Concept: Client's responsibility to maintain preconditions, not code's.
Example:
int daysEarlier(int y1, int m1, int d1, int y2, int m2, int d2)
// pre: isDate(y1, m1, d1) && isDate(y2, m2, d2)
// returns the number of days earlier the first date is than the second
Exception Handling
Definition: An exception is an object that denotes an unforeseen issue.
getMessagemethod provides description of the exception.
Types of Exceptions:
Checked (must be declared or caught): e.g.,
IOException.Unchecked: e.g.,
IllegalArgumentException.
Try-Catch Example:
try {
System.out.println("How old are you?");
int age= in.nextInt();
} catch (InputMismatchException exception) {
System.out.println("Input not well formed");
}
Exception Handling Methods
Specifying Exception Throws
Method declaration syntax for exceptions:
[accessSpecifier] returnType methodName( (parameterType parameterName)* ) throws ExceptionClass
Example Specification:
public void read(BufferedReader in) throws IOException
Creating Custom Exceptions
Process: Extend an exception class.
Example:
public class InsufficientFundsException extends RuntimeException {
public InsufficientFundsException() { }
public InsufficientFundsException(String message) { super(message); }
}
Usage Example:
void withdraw(int amount) {
if (amount > balance) {
throw new InsufficientFundsException(
"Withdrawal of " + amount + " exceeds balance of " + balance);
} else {
balance -= amount;
}
}
Exception Handling Synopses
Swallowing Exceptions:
try {
// actions that may throw exceptions
} catch (Exception e) {
// does nothing, not robust.
}
Avoidance Strategy: Never ignore exceptions; it hampers debugging and program reliability.
Summary of Key Points
Assertions: Used for invariants in a program; enforce conditions that must be true.
Exceptions: Address unpredictable scenarios; functionalities to maintain program robustness.
Distinction between handling assertions and exceptions is essential for developing reliable software.