Assertion not working

前端 未结 3 1369
北荒
北荒 2020-12-09 07:42

I am trying to write an Assertion to check if the size the user gives is a positive value, if not then make it positive, this statement is inside the class constructor which

3条回答
  •  爱一瞬间的悲伤
    2020-12-09 08:26

    You need to run your program with the -ea switch (enable assertions), otherwise no assert instructions will be run by the JVM at all. Depending on asserts is a little dangerous. I suggest you do something like this:

    public Grid(int size) {
        size = Math.max(0, size) 
        setLayout(new GridLayout(size, size));
        grid = new JButton[size][size];
    }
    

    Or even like this:

    public Grid(int size) {
        if(size < 0) {
            throw new IllegalArgumentException("cannot create a grid with a negative size");
        } 
        setLayout(new GridLayout(size, size));
        grid = new JButton[size][size];
    }
    

    The second suggestion has the benefit of showing you potential programming errors in other parts of your code, whereas the first one silently ignores them. This depends on your use case.

提交回复
热议问题