Java Reference
In-Depth Information
Listing 3-31.
Throwing an assertion error without a detail message
class AssertionDemo
{
public static void main(String[] args)
{
int x = 1;
assert x == 0;
}
}
Whenassertionsareenabled(Idiscussthistasklater),runningthepreviousapplica-
tion results in the following output:
Exception in thread "main" java.lang.AssertionError
at AssertionDemo.main(AssertionDemo.java:6)
In other situations, more information is eeded to help diagnose the cause of failure.
Forexample,suppose
expression1
comparesvariables
x
and
y
,andthrowsanerror
when
x
'svalueexceeds
y
'svalue.Becausethisshouldeverhappen,youwouldprobably
usethesecondstatementformtooutputthesevaluessoyoucoulddiagnosetheproblem.
Listing 3-32
demonstrates the second form of the assertion statement.
Listing 3-32.
Throwing an assertion error with a detail message
class AssertionDemo
{
public static void main(String[] args)
{
int x = 1;
assert x == 0: x;
}
}
Onceagain,itisassumedthatassertionsareenabled.Runningthepreviousapplica-
tion results in the following output:
Exception in thread "main" java.lang.AssertionError: 1
at AssertionDemo.main(AssertionDemo.java:6)
The value in
x
is appended to the end of the first output line, which is somewhat
cryptic.Tomakethisoutputmoremeaningful,youmightwanttospecifyanexpression
thatalsoincludesthevariable'sname:
assert x == 0: "x = "+x;
,forexample.