1 Specification
1.1 Specification structure
specification of a method consists of several clauses:
- a precondition , indicated by the keyword requires, is an obligation on the client.
- a postcondition , indicated by the keyword effects, is an obligation on the implementer.
1.2 Specifications in Java
preconditions into @param where possible, and postconditions into @return and @throws:
/**
* Find a value in an array.
* @param arr array to search, requires that val occurs exactly once
* in arr
* @param val value to search for
* @return index i such that arr[i] = val
*/
static int find(int[] arr, int val)
1.3 Null references
- null values are implicitly disallowed in parameters and return values.
- try to avoid null as much as possible.
1.4 Specifications for mutating methods
- a method should not modify its parameter.
- parameter could be declared with final key word.
- when writing a specification, use the convention that mutation is disallowed unless stated otherwise.
2 Exceptions
2.1 Exceptions for signaling bugs
- ArithmeticException , thrown for arithmetic errors like integer division by zero.
- NumberFormatException , thrown by methods like Integer.parseInt if you pass in a string that cannot be parsed into an integer.
2.2 Exceptions for special results
2.3 Checked and unchecked exceptions
Checked exceptions are called that because they are checked by the compiler:
- If a method might throw a checked exception, the possibility must be declared in its signature.
- If a method calls another method that may throw a checked exception, it must either handle it, or declare the exception itself, since if it isn’t caught locally it will be propagated up to callers.
- As a result, for an unchecked exception the compiler will not check for try - catch or a throws declaration.
2.4 Throwable hierarchy
- RuntimeException , Error , and their subclasses are unchecked exceptions. The compiler doesn’t require them to be declared in the throws clause of a method that throws them, and doesn’t require them to be caught or declared by a caller of such a method.
- All other throwables — Throwable , Exception , and all of their subclasses except for those of the RuntimeException and Error lineage — are checked exceptions. The compiler requires these exceptions to be caught or declared when it’s possible for them to be thrown.
2.5 Exception design considerations
- Exceptions are not just for signaling bugs. They can be used to improve the structure of code that involves procedures with special results.
- You should use an unchecked exception only to signal an unexpected failure (i.e. a bug), or if you expect that clients will usually write code that ensures the exception will not happen, because there is a convenient and inexpensive way to avoid the exception;
- Otherwise you should use a checked exception.
Reference
[1] 6.005 — Software Construction on MIT OpenCourseWare | OCW 6.005 Homepage at https://ocw.mit.edu/ans7870/6/6.005/s16/