[英]assert Vs if(var != null) which way is better or is correct?
In my app i want to close my cursor in finally statement like this : 在我的应用程序中,我想在finally语句中关闭光标,如下所示:
Cursor cursor = null;
try {
// some code
} finally {
cursor.close();
}
My IDE highlight cursor.close();
我的IDE突出显示
cursor.close();
and tell : 并告诉 :
This method can produce
nullPointerException
此方法可以产生
nullPointerException
And suggest to way to correct it (im using intelij idea) : 并提出纠正它的方法(即使用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 ? 我想知道它们之间有什么区别,哪种方法更好?
Java Assertions are only executed if -ea
(enable assertions) is passed as argument to the JVM. 仅在将
-ea
(启用断言)作为参数传递给JVM时才执行Java断言。 If assertions are enabled and the boolean expression of an assertion evaluates as false
,an AssertionError
will be thrown. 如果启用了断言并且断言的布尔表达式评估为
false
,则将抛出AssertionError
。 So assertions are really just useful as debugging feature. 因此断言实际上只是作为调试功能很有用。
You should definetely use the if
syntax. 您应该明确地使用
if
语法。
Note that there also is the syntax assert booleanFlag : message;
请注意,还有一种语法
assert booleanFlag : message;
which will pass message
as message to the AssertionException
if the booleanFlag is false
. 如果booleanFlag为
false
,它将把message
作为消息传递给AssertionException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.