/* Demonstrate assertions in Java * For the assertion to work, you must run with them enabled: * java -ea GPACalc * If the expression is False, then an AssertionError is thrown, with the error message (which is after the colon) */ public class GPACalc { public static double calc (double ary[]) { double sum = 0; for (double f : ary) { assert f >= 0.0 && f <= 4.3 : "Invalid value " + f; sum += f; } return sum/ary.length; } public static void main (String args[]) { double a[] = {3.5, 3.8, 4.0, 4.1, 4.5}; // try { System.out.println(calc(a)); // } catch (AssertionError e ) { // System.out.println( "Caught the assertion error. No crashing for you!" ); // } } }