请各位看以下这两个有关Assertion的问题:
Q29.
Given:
1. public class Test {
2. public static void main(String[] args) {
3. int x = 0;
4. assert (x > 0): “assertion failed”;
5. System.out.printIn(“finished”);
5. }
6. }
What is the result?
A. finished
B. Compilation fails.
C. An AssertionError is thrown.
D. An AssertionError is thrown and finished is output.
Answer: B.
这道题目的答案为什么是B呢?我只知道Assertion语句不能放在public方法中,这也包括main方法吗?是不是出现在public方法中的Assertion语句都会编译出错呢?
Q47.
Given:
20. public float getSalary(Employee e) {
21. assert validEmployee(e);
22. float sal = lookupSalary(e);
23. assert (sal>0);
24. return sal;
25. }
26. private int getAge(Employee e) {
27. assert validEmployee(e);
28. int age = lookupAge(e);
29. assert (age>0);
30. return age;
31. }
Which line is a violation of appropriate use of the assertion mechanism?
A. line 21
B. line 23
C. line 27
D. line 29
Answer: B.
这道题目为什么选择B答案呢?sal为调用lookupSalary(e)方法的返回值,23行用Assert语句判断sal是否大于0,这有什么不妥的地方吗?
是不是在public方法中都不好使用assert语句呢?如果有assert语句,那么编译会出错,是这样的吗?谢谢!!!
assert (x > 0): 的问题吧
的确是在哪理由不知道正确与否
21 要判断有没有效
23 要判断薪水
27 -21
29 要判断年龄
在public方法中可以使用assert语句
第一题绝对选 C
第2题应该选A,因为断言不适宜用来判断公共方法的参数的合法性,推荐用来判断私有方法的参数的合法性
相反,在任何方法中的结束处推荐用断言判断状态和返回值的合法性。