Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assert Vs if(var != null) which way is better or is correct?

Tags:

java

android

In my app i want to close my cursor in finally statement like this :

Cursor cursor = null;
try {
    // some code
} finally {
     cursor.close();
}

My IDE highlight cursor.close(); and tell :

This method can produce nullPointerException

And suggest to way to correct it (im using intelij idea) :
First:

assert cursor != null;
cursor.close();

Second:

if (cursor != null) {
   cursor.close();
} 

I want to know what is difference between them and which way is better approach ?

like image 352
YFeizi Avatar asked Feb 16 '15 15:02

YFeizi


People also ask

What does assert != null do in Java?

A lesser-known feature of assert is that you can append an error message. For example: assert o != null : "o is null"; This error message is then passed to the AssertionError constructor and ​printed along with the stack trace.

How do you assert non null?

Non-null assertion operatorpost-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded.

How do you assert something is null?

The assertNotNull() method means "a passed parameter must not be null ": if it is null then the test case fails. The assertNull() method means "a passed parameter must be null ": if it is not null then the test case fails. Save this answer.

How do you assert null in Testng?

#4) assertNullassert null is used to verify if the provided object contains a null value. It takes an object as the parameter and throws an AssertionError if the provided object does not hold a null value.


1 Answers

Java Assertions are only executed if -ea (enable assertions) is passed as argument to the JVM. If assertions are enabled and the boolean expression of an assertion evaluates as false,an AssertionError will be thrown. So assertions are really just useful as debugging feature.

You should definetely use the if syntax.

Note that there also is the syntax assert booleanFlag : message; which will pass message as message to the AssertionException if the booleanFlag is false.

like image 199
MinecraftShamrock Avatar answered Sep 30 '22 04:09

MinecraftShamrock