Assertions
Do not use assertions to validate arguments to a public method
Do use assertions to validate arguments to a private method
Please explain the difference between them?
Create two different classes namely General and CheckAssert.
public class General {
public static void main(String[] args) {
CheckAssert ca = new CheckAssert();
ca.call(0);
}
}
public class CheckAssert {
private void call(int i) {
assert (i>0);
System.out.println(i);
}
/*
public void call(int i) {
assert (i>0);
System.out.println(i);
}
Do not use assertions to validate arguments to a public method
*/
}
and compile
javac -source 1.4 CheckAssert.java
javac General.java
and execute
java -ea General
o/p
Exception in thread "main" java.lang.AssertionError
at CheckAssert.call(CheckAssert.java:4)
at General.main(General.java:5)
java General
o/p
0
If you need to validate public method arguments you will probably use exceptions to throw, say IllegalArgumentException if the values passed to the public method are invalid.
0 Comments:
Post a Comment
<< Home