<aside> 💡 Functions may have constraints on its parameters.
</aside>
We could check for these constraints by throwing an exception on checking the condition for the constraints on the parameters
public static double myfunc(double x) throws IllegalArgumentException{
// To Assume x >= 0
if( x < 0){
throw new IllegalArgumentException("x<0");
}
}
If myfunc
is only used internally in our own code.
Solution: Assert the property you assume to hold.
<aside>
💡 If assertions fails, code throws AssertionError
</aside>
public static double myfunc(double x){
assert x >= 0 : x;
}
<aside> 💡 This exception SHOULD NOT be CAUGHT.
</aside>
<aside> 💡 Assertions are enabled or disabled at runtime.
</aside>
It does not require recompilation.
Use the following flag to run with assertions enabled:
java -enableassertions MyCode
Can also use
-ea
as abbreviation for-enableassertions
/tuCan selectively turn on assertions for a class:
java -ea:Myclass MyCode
Can selectively turn on assertions for a package:
java -ea:in.ac.iitm.onlinedegree MyCode
Also, Disable assertions globally or selectively:
java -disableassertions MyCode
java -da:Myclass MyCode
Can combine as:
java -ea in.ac.iitm.onlinedegree -da:Myclass MyCode
Separate switch to enable assertions for system classes:
java -enablesystemassertions MyCode
or
java -esa MyCode