OO Programming with Java


Error handling

  1. The program must emit an UnavailableException that is defined in Java by a class than inherits from Exception:
public class UnavailableException extends Exception { }
  1. Next, the buy operation has to throws this exception when necessary:
public void buy(String name,int quantity) {
  for(Product book : this) {           // find product
    if (book.getName().equals(name)) { // String equality
      if (book.getQuantity()>=quantity) {
        book.buy(quantity);
        return;                        // exit operation
      }
      // Here: bad quantity !
      throw new UnavailableException();
    }
  }
  // Here: product not found ! SEE EXERCICES
}

go further

  1. And the operation has to notify that an exception can occur:
public void buy(String name,int quantity) throws UnavailableException { ... }

2 - 12