在我的应用程序中,我想在这样的 finally 语句中关闭我的光标:
Cursor cursor = null;
try {
// some code
} finally {
cursor.close();
}
我的 IDE 突出显示 cursor.close();
并告诉:
This method can produce
nullPointerException
并建议纠正它的方法(我使用的是 intelij idea):
第一:
assert cursor != null;
cursor.close();
第二:
if (cursor != null) {
cursor.close();
}
我想知道它们之间有什么区别,哪种方法更好?
最佳答案
Java 断言只有在 -ea
(启用断言)作为参数传递给 JVM 时才会执行。如果启用断言并且断言的 boolean 表达式计算为 false
,将抛出 AssertionError
。所以断言实际上只是用作调试功能。
你应该明确地使用 if
语法。
请注意还有语法 assert booleanFlag : message;
如果booleanFlag 为 false
。
关于java - assert 与 if(var != null) 哪种方式更好或正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28544382/