断言Vs if(var!= null)哪种方法更好或更正确?

YFe*_*izi 2 java android

在我的应用程序中,我想在finally语句中关闭光标,如下所示:

Cursor cursor = null;
try {
    // some code
} finally {
     cursor.close();
}
Run Code Online (Sandbox Code Playgroud)

我的IDE高亮显示cursor.close();

这种方法可以产生 nullPointerException

并提出纠正它的方法(使用intelij想法):
首先:

assert cursor != null;
cursor.close();
Run Code Online (Sandbox Code Playgroud)

第二:

if (cursor != null) {
   cursor.close();
} 
Run Code Online (Sandbox Code Playgroud)

我想知道它们之间有什么区别,哪种方法更好?

Min*_*ock 5

仅在将-ea(启用断言)作为参数传递给JVM 时才执行Java断言。如果启用了断言,并且断言的布尔表达式的值为falseAssertionError则将抛出an 。因此断言实际上只是作为调试功能很有用。

您应该明确使用if语法。

请注意,如果booleanFlag为,则还有语法assert booleanFlag : message;message作为消息传递给。AssertionExceptionfalse