运行结果如下: aClass.aMethod(
1 ): OK aClass.aMethod( -1 ): java.lang.AssertionError at
aClass.aMethod(aClass.java:3) at aClass.main(aClass.java:12) Exception in
thread
"main"
public
class Application{ static public void main( String args[] ) { //
BAD!! assert args.length == 3; int a = Integer.parseInt( args[0] ); int
b = Integer.parseInt( args[1] ); int c = Integer.parseInt( args[2]
); } }
public
class App{ static public void main( String args[] ) { if (args.length !=
3) throw new RuntimeException( "Usage: a b c" ); int a =
Integer.parseInt( args[0] ); int b = Integer.parseInt( args[1] ); int c =
Integer.parseInt( args[2]
); } }
public
class Connection{ private boolean isOpen = false; public void open()
{ // ... isOpen = true; } public void close() { //
BAD!! assert isOpen : "Cannot close a connection that is not open!"; //
... } }
public
class Connection{ private boolean isOpen = false; public void open()
{ // ... isOpen = true; } public void close() throws
ConnectionException { if (!isOpen) { throw new
ConnectionException( "Cannot close a connection that is not open!"
); } //
... } }
不要使用assertion来保证对用户提供的某项信息的要求
在下面这段代码里,程序员使用assertion来确保邮政编码有5或9位数字:
public
void processZipCode( String zipCode ) { if (zipCode.length() == 5) { //
... } else if (zipCode.length() == 9) { // ... } else { //
BAD!! assert false : "Only 5- and 9-digit zip codes
supported"; } }
public
class Connection{ private boolean isOpen = false; public void open()
{ // ... isOpen = true; // ... assert isOpen; } public void
close() throws ConnectionException { if (!isOpen) { throw new
ConnectionException( "Cannot close a connection that is not open!"
); } // ... isOpen = false; // ... assert
!isOpen; } }
private
int getValue() { if (/* something */) { return 0; } else if (/*
something else */) { return 1; } else { return 2; } } public
void method() { int a = getValue(); // returns 0, 1, or 2 if (a==0)
{ // deal with 0 ... } else if (a==1) { // deal with 1 ... } else if
(a==2) { // deal with 2 ... } else { assert false : "Impossible: a is
out of
range"; } } 这个例子中,getValue的返回值只能是0,1,2,正常时出现其他值的情形是不应该的,使用assertion来确保这一点是最合适的。