88

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

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Allain Lalonde
  • 91,574
  • 70
  • 187
  • 238

4 Answers4

176

You certainly can:

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

See Programming with Assertions for more information.

turbanoff
  • 2,439
  • 6
  • 42
  • 99
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
22
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.

matt burns
  • 24,742
  • 13
  • 105
  • 107
  • 3
    There is no point in wrapping every expression in brackets just because a ternary would otherwise be slightly confusing. If you happen to have a ternary expression as your assertion, you can wrap that. (Although I would argue that if you have a ternary expression as your assertion, you have probably messed up & at the very least you should extract the expression into a named method call for clarity.) – laszlok May 01 '18 at 09:25
12

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
  • 77,985
  • 20
  • 184
  • 180
8

If you use

assert Expression1 : Expression2 ;

Expression2 is used as a detail message for the AssertionError.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880