Using Assertions In Java

December 12, 2007 at 2:26 pm (Java)

Java’s new assertion mechanism, allows programmers to increase the robustness of their code by sprinkling it liberally with assert statements. The new assertion feature is easy to use, but any language feature, no matter how simple, can be used well or poorly. Here I’ll explain how to use Java’s assertion facility, and how not to misuse it.

Using assertions couldn’t be easier. Anywhere you can put a statement in Java, you can now write

assert boolExpr;

where boolExpr is any Boolean expression. If the expression is true, execution continues as if nothing happened. If it’s false, an exception is thrown. You can disable assertions at runtime if you wish, effectively removing them from your code.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: