Java's file-manipulation methods often indicate failure with a return value instead of throwing an exception. Consequently, programs that ignore the return values from file operations often fail to detect that those operations have failed. Java programs must check the return values of methods that perform file I/O. This is a specific instance of EXP00-J. Do not ignore values returned by methods.
Noncompliant Code Example (
This noncompliant code example attempts to delete a specified file but gives no indication of its success. The Java platform requires
File.delete() to throw a
SecurityException only when the program lacks authorization to delete the file [API 2014]. No other exceptions are thrown, so the deletion can silently fail.
This compliant solution checks the return value of
This compliant solution uses the
java.nio.file.Files.delete() method from Java SE 7 to delete the file:
The Java SE 7 Documentation [J2SE 2011] defines
Files.delete() to throw the following exceptions:
File does not exist
File is a directory and could not otherwise be deleted because the directory is not empty
An I/O error occurs
In the case of the default provider and a security manager is installed, the
SecurityException is a runtime exception, it need not be declared. Because
DirectoryNotExmptyException both inherit from
IOException, they will be caught by the compliant solution's
Failure to check the return values of methods that perform file I/O can result in unexpected behavior.
Ignored Return Value (Java)