[jsword-devel] java assertions

Joe Walker jsword-devel@crosswire.org
Fri, 09 Apr 2004 08:48:20 +0100


The interesting thing about assertions that is different from LogicError 
is that in normal use they don't unwind the stack. So there are times 
when we should alter things a bit.
The example I'm just looking at in common/...util.Convert.java had 
something like the following:

if (<TEST>)
{
     throw new LogicError();
}

<ACTION>

It might be tempting to change this to:

assert <TEST>;
<ACTION>

However the idea behind assert is that in devel test we get to know ASAP 
when something is not right, but if it goes wong in live then things 
might just be able to limp along. The code above will not limp on well 
if <ACTION> depends on <TEST> being false.
So we can do this:

if (<TEST>)
{
     assert false;
}
else
{
     <ACTION>
}

Joe.

DM Smith wrote:
> I was curious about java's assertions since I have not used them.
> http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html gives a 
> tutorial.
> According to 
> http://leepoint.net/notes-java/20language/30statements/40assertions/20assert-usage.html 
> :
>    You need to compile with the -source 1.4 flag to prevent assertions 
> from being compiled out.
>    You need to run the program with -ea or -enabledassertions as an 
> argument to the vm.
> 
> Because assertions may be compiled out, the test must be free of side 
> effects.
> 
> When the argument to an assert is false, it throws an AssertionError.
> A second argument can be supplied to an assertion to provide greater 
> detail that analysis of the code could not.
> 
> This can easily replace many uses of LogicError, but not when the 
> purpose is to rethrow caught Exception.
> 
> if (a == b)
> {
>    throw new LogicError("Oops");
> }
> 
> can become:
> assert a!=b;
> 
> However:
> try
> {
>    doit();
> }
> catch (Throwable t)
> {
>    throw new LogicError(t);
> }
> 
> would become:
> try
> {
>    doit();
> }
> catch (Throwable t)
> {
>    assert false : t.getMessage();
> }
> 
> _________________________________________________________________
> MSN Toolbar provides one-click access to Hotmail from any Web page – 
> FREE download! http://toolbar.msn.com/go/onm00200413ave/direct/01/
> 
> _______________________________________________
> jsword-devel mailing list
> jsword-devel@crosswire.org
> http://www.crosswire.org/mailman/listinfo/jsword-devel