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

JavaAssert

Java Problem Overview


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)?

Java Solutions


Solution 1 - Java

You certainly can:

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

See Programming with Assertions for more information.

Solution 2 - Java

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.

Solution 3 - Java

It absolutely does:

assert importantVar != null : "The important var was null!";

This will add "The important var was null" to the exception that is thrown.

Solution 4 - Java

If you use

assert Expression1 : Expression2 ;

Expression2 is used as a detail message for the AssertionError.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAllain LalondeView Question on Stackoverflow
Solution 1 - JavaGreg HewgillView Answer on Stackoverflow
Solution 2 - Javamatt burnsView Answer on Stackoverflow
Solution 3 - JavaJason CocoView Answer on Stackoverflow
Solution 4 - JavaBill the LizardView Answer on Stackoverflow