tags:

views:

598

answers:

5

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

Currently an AssertionError gets thrown, but I don't think you have the power to specify a custom message for it.

Am I wrong?

If I am please correct me, and if I'm correct can you provide a mechanism for doing this (other than creating your own exception type and throwing it).

+20  A: 

You certainly can:

assert x > 0 : "x is greater than zero, x=" + x;

See Programming with Assertions for more information.

Greg Hewgill
+5  A: 

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.

Jason Coco
+4  A: 

If you use

assert Expression1 : Expression2 ;

Expression2 is used as a detail message for the AssertionError.

Bill the Lizard
+1  A: 

As a side note, JUnit gives you a whole set of new assertion functions. Of course, they're intended for use in unit testing...

R. Bemrose
A: 
assert (condition) : "some message";

I'd recommend putting the conditional in brackets

assert (y > x): "y is too big. 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.

floater81