5

I am using FindBugs to analyze my code in Eclipse from Ant.

Following snippet gives RV_RETURN_VALUE_IGNORED_BAD_PRACTICE:

RV: Method ignores exceptional return value (RV_RETURN_VALUE_IGNORED_BAD_PRACTICE)

This method returns a value that is not checked. The return value should be checked since it can indicate an unusual or unexpected function execution. For example, the File.delete() method returns false if the file could not be successfully deleted (rather than throwing an Exception). If you don't check the result, you won't notice if the method invocation signals unexpected behavior by returning an atypical return value.

public void export (File file) throws IOException {
    if (!file.exists()) {
        file.createNewFile();
    }

    BufferedWriter bw = null;
    try {
        bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
    ...

Actually I don't care where file existed or not, the method should keep executing. If exception happened it would be thrown outside of export()

How can I rewrite this snippet, so warning/error is not shown, without disabling it in Findbugs config file?

Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101

2 Answers2

5

In that particular case, you don't have to call file.createNewFile() because the file will be created anyway by FileWriter.

However, you must assure that the parent folder for the file exists.

Danubian Sailor
  • 1
  • 38
  • 145
  • 223
  • Yes, just remove the `if` altogether. But I wonder why anyone wouldn't care if his program works in the first place. – Axel Mar 08 '13 at 07:59
4

f.createNewFile(); returns boolean value

true if the named file does not exist and was successfully created; false if the named file already exists

change method to boolean result = f.createNewFile();

You should probably change the code if you do not care whether the file exists or not to exclude the check for exists and directly creating BufferedWriter which will create the file if it does not exist. Also if you still want to go with the present code add SuppressWarnings to ignore the warning.

Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
  • "returns boolean value" I know, but it would not eliminate the message if `result` is not handled differently. – Nikolay Kuznetsov Mar 08 '13 at 07:50
  • 1
    if you dont care then you can ignore them using `SuppressWarnings`. http://stackoverflow.com/questions/1829904/is-there-a-way-to-ignore-a-single-findbugs-warning I will also edit my post for that, – Narendra Pathai Mar 08 '13 at 07:53