6

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 ?

YFeizi
  • 1,498
  • 3
  • 28
  • 50
  • 2
    Possible duplicate of http://stackoverflow.com/questions/2758224/assertion-in-java – tsnorri Feb 16 '15 at 15:08
  • 2
    `assert` will crash your app if `cursor` is `null`, either because the assertion itself will trigger an exception, or if it is disabled, you will get a `NullPointerException`. The `if` check will not. – CommonsWare Feb 16 '15 at 15:09
  • thank you @CommonsWare , then i must use `if` if i understand correctly :) – YFeizi Feb 16 '15 at 15:12
  • 1
    If `Cursor` implements `AutoCloseable` and your Android minSdkLevel is >= 19 (so Java 7 language features are available), this question becomes moot because you should be using try-with-resources instead: `try (Cursor cursor = ...) { // some code }`. – Philipp Reichart Feb 16 '15 at 15:22

1 Answers1

10

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.

MinecraftShamrock
  • 3,504
  • 2
  • 25
  • 44
  • 1
    I would add that (in this case) it is even _semantically wrong_ to use an assert, since it can happen that the cursor is null and that does not have to be the programmer's fault. You don't want to fail fast here, you don't want the program to fail. – Lovis Feb 16 '15 at 18:12