// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.util.Random;

public class ReturnValueOrException {
    private static Random rng = new Random();
    public static boolean retval(double lim) {
        if(rng.nextDouble() < lim) {
            return false;
        } else {
            return true;
        }
    }
    public static void excep(double lim) throws RetValException{
        if(rng.nextDouble() < lim) {
            throw new RetValException();
        }
    }
    private static final int N = 10000000;
    public static void timeRetval(double lim) {
        int err = 0;
        long t1 = System.currentTimeMillis();
        for(int i = 0; i < N; i++) {
            if(!retval(lim)) {
                err++;
            }
        }
        long t2 = System.currentTimeMillis();
        System.out.println("retval / " + lim + " : " + (t2 - t1) + " (" + err/(double)N + ")");
    }
    public static void timeExcep(double lim) {
        int err = 0;
        long t1 = System.currentTimeMillis();
        for(int i = 0; i < N; i++) {
            try {
                excep(lim);
            } catch(RetValException ex) {
                err++;
            }
        }
        long t2 = System.currentTimeMillis();
        System.out.println("excep / " + lim + " : " + (t2 - t1) + " (" + err/(double)N + ")");
    }
    public static void test(double lim) {
        timeRetval(lim);
        timeExcep(lim);
    }
    public static void main(String[] args) {
        test(0);
        test(0.001);
        test(0.01);
        test(0.1);
        test(1);
    }
}

class RetValException extends Exception {
}
