The Artima Developer Community
Sponsored Link

James Gosling on Java, May 2001
A Conversation with Java's Creator, James Gosling
by Bill Venners
First Published in JavaWorld, June 2001

<<  Page 11 of 22  >>


Assertions versus Exceptions

Bill Venners: In 1.4, assertions are due to come into Java.

James Gosling: Yeah.

Bill Venners: I'm curious when you would use assertions versus when you would use exceptions.

James Gosling: Assertions are just a syntax for generating exceptions. When an assertion fails, an exception gets tossed. So, an assertion in Java is essentially: if this funny condition isn't true, then throw an exception. At its heart, that's what an assertion is.

Standard assert macros in C and C++ have all done basically that. So the assert statement is not actually adding anything really new. What it's adding is a somewhat easier notation, and there's some other stuff under the sheets for enabling and disabling them.

Bill Venners: If the main purpose of assertions is to streamline the process of me checking for things and throwing exceptions, should I remove that at run time?

James Gosling: One of the nice things about the way Java works is that in general people ship around Java class files and the compilation phase happens just in time. These JIT compilers are all over the place. One of the really nice things you can do with that, which the assertion facility uses very heavily, is the code you ship around has the assertions in it. Assertions look like: if my gnarly test fails, then throw the exception. It gets turned into roughly: if assertions are enabled and my test fails, throw the exception.

And the first clause in there, the "if assertions are enabled," is generated in such a way that most just-in-time compilers will go, "Oh, that is statically false, so false and anything is false, so I don't have to evaluate the assertion condition, and since the if is false, the then clause can never be executed." So the whole thing just drops out. You can deliver your code with all the assertion tracking enabled in it, then, and at run time when you go to launch the app, you can say, "Turn off assertions."

Bill Venners: To improve performance?

James Gosling: To improve performance. And one of the great beauties of that is you can deliver one library to people rather than a debug library and a regular library. And they can decide.

<<  Page 11 of 22  >>

Sponsored Links

Copyright © 1996-2018 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use