Source of RandomThrower.java


  1: import java.util.Random;
  2: import java.util.List;
  3: import java.util.ArrayList;
  4: import java.util.NoSuchElementException;

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

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

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

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

 39: }