Java Reference
In-Depth Information
introduce the syntax now. The following example shows how to open a file using the
FileInputStream
class (which results in an object which will require cleanup):
try
(
InputStream
is
=
new
FileInputStream
(
"/Users/ben/details.txt"
))
{
// ... process the file
}
This new form of
try
takes parameters that are all objects that require cleanup.
2
These objects are scoped to this
try
block, and are then cleaned up automatically no
matter how this block is exited. The developer does not need to write any
catch
or
finally
blocks—the Java compiler automatically inserts correct cleanup code.
All new code that deals with resources should be written in the TWR style—it is
considerably less error prone than manually writing
catch
blocks, and does not suf‐
fer from the problems that plague techniques such as finalization (see
“Finalization”
on page 206
for details).
The assert Statement
An
assert
statement is an attempt to provide a capability to verify design assump‐
tions in Java code. An
assertion
consists of the
assert
keyword followed by a
boolean expression that the programmer believes should always evaluate to
true
. By
default, assertions are not enabled, and the
assert
statement does not actually do
anything.
It is possible to enable assertions as a debugging tool, however; when this is done,
the
assert
statement evaluates the expression. If it is indeed
true
,
assert
does
nothing. On the other hand, if the expression evaluates to
false
, the assertion fails,
and the
assert
statement throws a
java.lang.AssertionError
.
Outside of the core JDK libraries, the
assert
statement is
extremely
rarely used. It turns out to be too inflexible for test‐
ing most applications and is not often used by ordinary devel‐
opers, except sometimes for field-debugging complex multi‐
threaded applications.
The
assert
statement may include an optional second expression, separated from
the first by a colon. When assertions are enabled and the first expression evaluates
to
false
, the value of the second expression is taken as an error code or error mes‐
sage and is passed to the
AssertionError()
constructor. The full syntax of the
statement is:
assert
assertion
;
or:
assert
assertion
:
errorcode
;
2
Technically, they must all implement the
AutoCloseable
interface.