如何用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();
    }

===============>>#1 票数:5 已采纳

断言大致等于:

if (!condition) {
    throw new AssertionError();
}

===============>>#2 票数: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();

请注意,有抛出一个区分ExceptionError - Exception s的意思是捕捉和处理进一步上升,而Error小号指示的情况下,你不能歇着。 例如,如果无法恢复失败的检查,则可以考虑定义并使用MyValidationError

===============>>#3 票数: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();
    }

  ask by Ariel Grabijas translate from so

未解决问题?本站智能推荐:

关注微信公众号