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 ?
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.
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.
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.
#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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With