Java Reference
In-Depth Information
44. Do not use assertions to verify the absence of runtime errors
Diagnostic tests can be incorporated into programs by using the assert statement. Asser-
tions are primarily intended for use during debugging and are often turned off before
code is deployed by using the -disableassertions (or -da ) Java runtime switch. Con-
sequently,assertionsshouldbeusedtoprotectagainstincorrectprogrammerassumptions,
and not for runtime error checking.
Assertions should never be used to verify the absence of runtime (as opposed to logic)
errors, such as
Invalid user input (including command-line arguments and environment vari-
ables)
File errors (for example, errors opening, reading, or writing files)
Network errors (including network protocol errors)
Out-of-memory conditions (when the Java Virtual Machine cannot allocate space
for a new object, and the garbage collector cannot make sufficient space avail-
able)
System resource exhaustion (for example, out-of-file descriptors, processes,
threads)
System call errors (for example, errors executing files or locking or unlocking
mutexes)
Invalid permissions (for example, file, memory, user)
Code that protects against an I/O error, for example, cannot be implemented as an as-
sertion because it must be present in the deployed executable.
Assertions are generally unsuitable for server programs or embedded systems in de-
ployment. A failed assertion can lead to a denial-of-service (DoS) attack if triggered by a
malicioususer.Insuchsituations,asoftfailuremode,suchaswritingtoalogfile,ismore
appropriate.
Noncompliant Code Example
Thisnoncompliantcodeexampleusesthe assert statementtoverifythatinputwasavail-
able:
Click here to view code image
BufferedReader br;
Search WWH ::




Custom Search