Source of RandomThrower.java


  1: package exceptions;

  3: import java.util.Random;
  4: import java.util.List;
  5: import java.util.ArrayList;
  6: import java.util.NoSuchElementException;

  8: /**
  9:  * Throw an exception chosen randomly from a list.
 10:  *
 11:  * @author Mark Young (A00000000)
 12:  */
 13: public class RandomThrower {

 15:     private static final List<Exception> list = new ArrayList<>();
 16:     private static final Random rand = new Random();

 18:     /**
 19:      * Add an exception to the list.
 20:      *
 21:      * @param except the exception to add
 22:      */
 23:     public static void add(Exception except) {
 24:         list.add(except);
 25:     }

 27:     /**
 28:      * Choose an exception at random.
 29:      *
 30:      * @throws Exception an exception chosen at random from the current list
 31:      */
 32:     public static void randomThrow() 
 33:             throws Exception {
 34:         if (list.isEmpty()) {
 35:             throw new NoSuchElementException("There's nothing in the list!");
 36:         }
 37:         int posn = rand.nextInt(list.size());
 38:         throw list.get(posn);
 39:     }

 41: }