HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

"Implementing Assertions in Java"
Vol. 2, Issue 12, p. 52

	

Listing 1. 

import assertion.*; 
public class Example { 
    public static void main (String args []) { 
        Example e = new Example(); 
        e.test(1, 2); 
        e.test(2, 1); 
    } 

    public void test(int a, int b) { 
System.out.println("In test with " + a + " and " + b); 
        Assertion.assert(a < b); 
} 
} 

Listing 2. 

>java Example 
In test with 1 and 2 
In test with 2 and 1 
assertion.AssertionException: Failed assertion 
        at assertion.Assertion.assert(Assertion.java:41) 
        at Example.test(Example.java:11) 
        at Example.main(Example.java:7) 

Listing 3. 

public class Assertion { 
    /* Don't make assertion instances */ 
    Assertion () {}; 

public static void assert (boolean bool) throws AssertionException { 
        if (!bool) 
            throw new AssertionException("Failed assertion"); 
} 
  

public static void assert (boolean bools []) throws AssertionException { 
        for (int i = 0; i < bools.length; i++) { 
            assert(bools[i]); 
        } 
} 
} 

Listing 4. 

public class AssertionException extends RuntimeException { 
    AssertionException () { 
        this("Assertion exception"); 
    } 
    AssertionException (String information) { 
        super(information); 
    } 
} 

Listing 5: CheckedAssertion class. 

public class CheckedAssertion { 
/* Don't make checked assertion instances */ 
CheckedAssertion () {}; 

public static void assert (boolean bool)  
throws CheckedAssertionException { 
        if (!bool) 
            throw new CheckedAssertionException("Failed assertion"); 
    } 

public static void assert (boolean bools [])  
throws CheckedAssertionException { 
        for (int i = 0; i < bools.length; i++) { 
            assert(bools[i]); 
        } 
    } 
} 

Listing 6: CheckedAssertionException class. 


public class CheckedAssertionException extends Exception { 
    CheckedAssertionException () { 
        this("CheckedAssertion exception"); 
    } 
    CheckedAssertionException (String information) { 
        super(information); 
    } 
}
 

 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.