Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can java's assert statement allow you to specify a message?

Tags:

java

assert

Seems likes it might be useful to have the assert display a message when an assertion fails.

Currently an AssertionError gets thrown, can you specify a custom message for it?

Can you show an example mechanism for doing this (other than creating your own exception type and throwing it)?

like image 294
Allain Lalonde Avatar asked Nov 07 '08 20:11

Allain Lalonde


People also ask

What does an assert statement do?

assert statement takes an expression and optional message. assert statement is used to check types, values of argument and the output of the function. assert statement is used as debugging tool as it halts the program at the point where an error occurs.

What does assert () do in Java?

An assertion is a statement in Java which ensures the correctness of any assumptions which have been done in the program. When an assertion is executed, it is assumed to be true. If the assertion is false, the JVM will throw an Assertion error. It finds it application primarily in the testing purposes.

What is the advantage of assertion and where we should not use it?

According to Sun Specification, assertion should not be used to check arguments in the public methods because it should result in appropriate runtime exception e.g. IllegalArgumentException, NullPointerException etc. Do not use assertion, if you don't want any error in any situation.

Can we use assert instead of if statement?

That an “Assert” is used only for validations, where an “If” clause is used for the logic within our code. We can use an “If” clause to determine whether our automation should follow one path or another, but an “Assert” statement to validate the elements within those paths.


2 Answers

You certainly can:

assert x > 0 : "x must be greater than zero, but x = " + x; 

See Programming with Assertions for more information.

like image 93
Greg Hewgill Avatar answered Oct 22 '22 04:10

Greg Hewgill


assert (condition) : "some message"; 

I'd recommend putting the conditional in brackets

assert (y > x): "y is too small. y = " + y; 

Imagine if you came across code like this...

assert isTrue() ? true : false : "some message"; 

Don't forget this has nothing to do with asserts you'd write in JUnit.

like image 44
matt burns Avatar answered Oct 22 '22 03:10

matt burns