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

Allain Lalonde picture Allain Lalonde · Nov 7, 2008 · Viewed 36k times · Source

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

Answer

Greg Hewgill picture Greg Hewgill · Nov 7, 2008

You certainly can:

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

See Programming with Assertions for more information.