Assertion not working

26,910

Solution 1

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.

Solution 2

Assertions can be enabled or disabled when the program is started, and are disabled by default.

See Enabling and Disabling Assertions

In short, to enable assertions in all classes, except System classes, use the -enableassertions, or -ea, switch when you run your class.

Solution 3

Since assert is a new Java keyword introduced in JDK 1.4, you have to compile the program using a JDK 1.4 compiler. Furthermore, you need to include the switch –source 1.4 in the compiler command as follows:

javac –source 1.4 AssertionDemo.java

NOTE: If you use JDK 1.5 or later, there is no need to use the –source 1.4 option in the command.

By default, the assertions are disabled at runtime. To enable it, use the switch –enableassertions, or –ea for short, as follows:

java –ea AssertionDemo

Assertions can be selectively enabled or disabled at class level or package level. The disable switch is –disableassertions or –da for short.

For example, the following command enables assertions in package package1 and disables assertions in class Class1.

java –ea:package1 –da:Class1 AssertionDemo

Assertion should not be used to replace exception handling. Exception handling deals with unusual circumstances during program execution. Assertions are to assure the correctness of the program. Exception handling addresses robustness and assertion addresses correctness. Like exception handling, assertions are not used for normal tests, but for internal consistency and validity checks.

So In this case, best answer is exception handling.

Do not use assertions for argument checking in public methods. Valid arguments that may be passed to a public method are considered to be part of the method’s contract. The contract must always be obeyed whether assertions are enabled or disabled. For example, the above code should be rewritten using exception handling

Share:
26,910

Related videos on Youtube

Sam Palmer
Author by

Sam Palmer

Studying PhD in Computational Finance and Financial Mathematics, with a focus on parallel computing and custom hardware.

Updated on July 09, 2022

Comments

  • Sam Palmer
    Sam Palmer almost 2 years

    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 takes the size value and then makes an array[size]. I have written the below code which i believe to be correct.

        public Grid(int size) {
    
    
        try{
            assert size > 0 ;
        }
        catch(AssertionError e){
            size = Math.abs(size);
        }
    
        setLayout(new GridLayout(size, size));
        grid = new JButton[size][size];
    }
    

    Though I never seems to evaluate my assertion and continues the program then causes the NegativeArraySize error( which i am trying to avoid)

    I also tried just

    assert size>0;
    

    And the program fails to stop for negative values..

    I have had a few problems with running java on mac recently, so i don't know if my code is right or if it is just one of those odd mac quirks!! and should just use

    size=Math.abs(size);
    

    Thanks Sam,

  • Sam Palmer
    Sam Palmer over 12 years
    Smashing stuff!, quick question, can this be enabled in the java code itself or is purely a command line statement?
  • Matt
    Matt over 12 years
    It's purely a switch for the command line: java -ea com.foo.bar.MyClass
  • xoxox
    xoxox about 7 years
    The first part is BAD. If someone passes a negative number to the constructor, its most likely because of a bug and this should not be hidden/silently corrected! Also, when writing code like this, the assumed value could differ from the actual value!
  • Matt
    Matt about 7 years
    @xoxox That's exactly what is mentioned in the last sentence of my answer: "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.". This implies that the second solution is more favorable. Mind explaining the downvote?
  • xoxox
    xoxox about 7 years
    "This depends on your use case." Why would you prefer the first one?
  • Matt
    Matt about 7 years
    I really don't prefer the first one. It's conceptually as close as possible to the code of the OP for educational purposes. From a stylistic point it's definitely the second solution IMHO. That's why added it. Which point are you trying to make, not covered in my answer?