Wednesday, August 29, 2007

Java 1.4: ASSERTIONS

Assertions provide a convenient mechanism for verifying that a class's methods are called correctly. This mechanism can be enabled or disabled at runtime. The intention is that assertions typically be enabled during development and disabled in the field.

Assertions has the following syntax:

assert Expression1;
assert Expression1 : Expression2;

  • Expression1 must be boolean type.
  • Expression2 may have any type.
  • If assertions are disables at runtime (default state) then assert statement does nothing.
  • If assertions are enabled at runtime( using command line argument to JVM) then Expression1 is evaluated. If it is true, no further action is taken. If it is false then AssertionError is thrown. If Expression2 is present, it is passed to constructor of the AssertionError where it is converted to String and used as a error message.

No comments: