2

如何用 if 替换断言?例子:

public Wezel<Wartosc,Indeks> getWujek() 
    {
        assert rodzic != null; // Root node has no uncle
        assert rodzic.rodzic != null; // Children of root has no uncle
        return rodzic.getBrat();
    }
4

3 回答 3

5

一个断言大致等价于:

if (!condition) {
    throw new AssertionError();
}
于 2011-12-11T17:30:15.223 回答
2

替换这些断言将采用以下验证的形式:

if (rodzic == null)
   throw new MyValidationException("rodzic cannot be null");
if (rodzic.rodzic == null)
   throw new MyValidationException("rodzic.rodzic cannot be null");
return rodzic.getBrat();

请注意,投掷 anException和 an Error- Exceptions 是为了在更远的地方被捕获和处理,而Errors 表示您无法恢复的情况。例如,MyValidationError如果失败的检查不可恢复,您可能会考虑定义和使用 a。

于 2011-12-11T17:30:41.267 回答
2
public Wezel<Wartosc,Indeks> getWujek() 
    {
        if(rodzic == null) { // Root node has no uncle
            throw new Exception("Root node has no uncle");
        }
        if(rodzic.rodzic == null) {
            throw new Exception("Children of root have no uncle");
        }
        return rodzic.getBrat();
    }
于 2011-12-11T17:32:37.103 回答