cs205: engineering software? (none) 20 September 2010

## CS205 Notes 6 (4 September 2006)

cs205 Monday 4 September 2006

 Assignments Due
• Today: remaining reading for ps2: Chapter 4, Chapter 10 through 10.2, and Chapter 5 through section 5.2
• Friday, 8 September: Problem Set 2

### Exceptions

Here is an implementation of the mode procedure from Quiz 1:
```public class Quiz {
static public int mode (int[] a)
// REQUIRES: a has at least one element
// EFFECTS: Returns a value m such that m is an element of a,
//    and no other value appears more often than m in a.
{
int best = a[0];
int bestcount = 1;

for (int i = 0; i < a.length; i++) {
int val = a[i];
int count = 0;
for (int j = 0; j < a.length; j++) {
if (a[j] == val) {
count++;
}
}
if (count > bestcount) {
best = val;
bestcount = count;
}
}
return best;
}

static public void main (String [] args) {
int [] tarray1 = { 1, 2, 2, 3, 2, 5 };
int [] tarray2 = { };

System.out.println ("Mode tarray1: " + mode(tarray1));
System.out.println ("Mode tarray2: " + mode(tarray2));
}
}
```
Explain what happens when the test main procedure runs.

What are advantages of using Exceptions (and specifying exceptional behaviors in the EFFECTS clause) over using REQUIRES clauses?

What are advantages of REQUIRES clauses over using Exceptions?

```static public int mode(int[] a) throws NoModeException
// EFFECTS: If a does not contain at least one element, throws
//    NoModeException.  Otherwise, returns a value v such
//    that v is an element of a, and no other value appears
//    in a more frequently than v does.

{
if (a == null || a.length == 0) {
throw new NoModeException ();
}
... // same as before
}
```
We need to contain all calls to mode in a try block. Which of these is better?
```   ...
try {
System.out.println("Mode tarray1: " + mode(tarray1));
} catch (NoModeException nme) {
System.err.println("Error: " + nme);
}

try {
System.out.println("Mode tarray2: " + mode(tarray2));
} catch (NoModeException nme) {
System.err.println("Error: " + nme);
}
```
or:
```  ...
try {
System.out.println("Mode tarray1: " + mode(tarray1));
System.out.println("Mode tarray2: " + mode(tarray2));
} catch (NoModeException nme) {
System.err.println("Error: " + nme);
}
```