GitHub
CERT Secure Coding

ERR02-J. Prevent exceptions while logging data

Exceptions that are thrown while logging is in progress can prevent successful logging unless special care is taken. Failure to account for exceptions during the logging process can cause security vulnerabilities , such as allowing an attacker to conceal critical security exceptions by preventing them from being logged. Consequently, programs must ensure that data logging continues to operate correctly even when exceptions are thrown during the logging process.

Noncompliant Code Example

This noncompliant code example writes a critical security exception to the standard error stream:

Non-compliant code
try {
  // ...
} catch (SecurityException se) {
  System.err.println(se);
  // Recover from exception
}

Writing such exceptions to the standard error stream is inadequate for logging purposes. First, the standard error stream may be exhausted or closed, preventing recording of subsequent exceptions. Second, the trust level of the standard error stream may be insufficient for recording certain security-critical exceptions or errors without leaking sensitive information. If an I/O error were to occur while writing the security exception, the catch block would throw an IOException and the critical security exception would be lost. Finally, an attacker may disguise the exception so that it occurs with several other innocuous exceptions.

Using Console.printf() , System.out.print*() , or Throwable.printStackTrace() to output a security exception also constitutes a violation of this rule.

Compliant Solution

This compliant solution uses java.util.logging.Logger , the default logging API provided by JDK 1.4 and later. Use of other compliant logging mechanisms, such as log4j, is also permitted.

Compliant code
try {
  // ...
} catch(SecurityException se) {
  logger.log(Level.SEVERE, se);
  // Recover from exception
}

Typically, only one logger is required for the entire program.

Risk Assessment

Exceptions thrown during data logging can cause loss of data and can conceal security problems.

Rule Severity Likelihood Detectable Repairable Priority Level
ERR02-J Medium Likely Yes No P12 L1

Automated Detection

ToolVersionChecker

Description

CodeSonar
9.0p0

JAVA.DEBUG.LOG

Debug Warning (Java)

Parasoft Jtest
2025.2
CERT.ERR02.SIOAvoid calling print methods of 'System.err' or 'System.out'
Security Reviewer - Static Reviewer

6.02

Securitymisc16Full Implementation
SonarQube
9.9
S106Standard outputs should not be used directly to log anything

HARMONY-5981 describes a vulnerability in the HARMONY implementation of Java. In this implementation, the FileHandler class can receive log messages, but if one thread closes the associated file, a second thread will throw an exception when it tries to log a message.

Bibliography

[ API 2014 ]

Class Logger

[ JLS 2015 ]

Chapter 11, "Exceptions"

[ Ware 2008 ]