Difference between java ' assert 'and '

2020-07-11 09:27发布

问题:

what is the difference between java assert and if () {} else exit;?

can i just use if () {} else exit instead of assert ?

回答1:

A bit of google maybe ?

" The main thing you should keep in mind is that the if-else statement should be used for program flow control and the assert keyword should only be used for testing purposes. You should never use asserts to actually perform any operation required for your application to work properly. According to Sun's official Java documentation: "Each assertion contains a boolean expression that you believe will be true when the assertion executes." "

Read more: http://wiki.answers.com/Q/What_is_the_difference_between_assert_keyword_and_if_keyword_in_java#ixzz1v2GGfAhq



回答2:

you could, assert is specifically designed to assert some part of code,

assert will throw AssertionError if it fails to assert


Also See

  • assert reference


回答3:

I can just ignore the assertion

class A{

public static void main(String[] args) {
    assert false;
  System.out.println("hi");
}
}

This code will print hi by default

$ java -cp . A
hi
$ java -ea -cp . A
Exception in thread "main" java.lang.AssertionError
    at A.main(A.java:6)


回答4:

if-else is for controlling the flow of your program. assert must not be used for this! Asserts are just for having "checkpoints" in your code to check conditions which "should always" match.

Asserts can be turned on or off when running a program so that you could enable the asserts on your development machine/integration environment and disable them in the released version.



回答5:

The assert keyword will only trigger an exception when you enable the assertions with -ea on the command line. The if/else will always execute. On top of that the assert keyword allows to write less verbose code. Compare:

assert parameter != null;

to:

if( parameter != null )
{

}
else
{

}


回答6:

can i just use if () {} else exit instead of assert ?

Yes you could, but ...

  • you wouldn't be able to turn of the test unless you made the condition depend on an extra flag (which makes it more complicated, etc),

  • you wouldn't get a chance to perform tidy-up in any enclosing finally block,

  • it would be more complicated to log the cause of the problem than if an AssertionError (or any other exception) was thrown, and

  • if your code needed to be reused (as-is) in another application, your calls to exit could be problematic.



回答7:

Asserts are ignored unless the -ea param is passed:

java -ea myjar.jar

That way, you can use them when you are testing your application, but ignore them at other times.



标签: java assert