使用断言添加前置条件和后置条件



这是我正在处理的任务。其中一个要求是向SomeClass添加前置和后置条件。我仍在学习什么是前置条件和后置条件,但更重要的是,我如何实施它们?

最初的赋值问题是:"编写一个程序,显示构造函数将有关构造函数失败的信息传递给异常处理程序。定义类SomeClass,它会在构造函数中引发异常。您的程序应该尝试创建SomeClass类型的对象,并捕获从构造函数引发的异常。

import java.util.Scanner;
public class Demo3 {
    public static void main(String[] args) {
        Scanner scan=new Scanner(System.in);
        System.out.println("Enter a number between 0 and 10:");
        int a=scan.nextInt();
        System.out.println("Enter another number between 0 and 10:");
        int b=scan.nextInt();
        SomeClass testException;
        try
        {
            testException = new SomeClass(a,b);
        }
        catch(Exception e)
        {
           System.out.println("Exception occurred: "+e.getMessage());
        }
    }
}
public class SomeClass {
    int a;
    int b;
    public SomeClass (int a, int b) throws Exception {
        assert (a >= 0 && a <= 10) : "bad number: " + a;
        if(a<0 || a > 10){System.out.println("Try again!");}
        assert (b >= 0 && b <= 10) : "bad number: " + b;
        if(b<0 || b > 10){System.out.println("Try again again!");}
        throw new Exception("You've got an error!");
    } 
}

assert语句在失败时将抛出一个AssertionError。但是assert语句必须使用JVM参数手动启用,因为它们在生产代码中默认是关闭的。这不适合你的任务。

如果你的要求是抛出AssertionError,那么你可以明确抛出:

public SomeClass (int a, int b) { 
    if (a < 0 || a > 10) {
        throw new AssertionError("the first param is out of valid range: " + a);
    }
    if (b < 0 || b > 10) {
        throw new AssertionError("the second param is out of valid range: " + b);
    }
    // at this point the pre-conditions have been validated
    this.a = a;
    this.b = b;
}

我省略了throws子句,因为AssertionError不是已检查的异常,不需要声明它

最后,在您的代码中,作为构造函数的最后一条语句的throw new Exception("You've got an error!");at将始终运行,即使参数是正确的。因此,这种说法没有任何意义。

最新更新