...
This noncompliant code example attempts to rename a given file if it exists, perform operations on the renamed file, and then delete the renamed file. However, because of the short-circuit behavior of the ||
operator, the renameTo()
method does not execute when the exists()
method returns true
. Because of this, the renamed file may or may not exist, which may result in an attempt to use and then delete a nonexistent file. This problem is exacerbated by the fact that File.delete()
does not throw an exception but returns an error code on failure, which is sometimes silently ignored or perceived as unnecessary. (See EXP02 EXP00-J. Do not ignore values returned by methods)
Code Block | ||
---|---|---|
| ||
class BadRenameFile { public static void main(String[] args) { File fOriginal = new File("original.txt"); File fNew = new File("new.txt"); if(fOriginal.exists() || fOriginal.renameTo(fNew)) { // do something with fNew fNew.delete(); } } } |
...