JAVA警告 - 去除可能的空指针.我该如何正确摆脱这个警告?

Bil*_*ith 0 java null dereference

我正在学习JAVA.

我似乎无法找到摆脱这种'可能的null derefence'警告的方法.我已经在适当的范围内创建了fOut为null,否则我得到一个'可能没有被初始化'错误.

我无法找到一个简单的例子来帮助我解决这个问题.我知道这可能是一个简单的答案.

谢谢.

public static int waveToFile (String filename, byte[] byteWave)
{
    FileOutputStream fOut = null;


    File file = new File (filename);
    try
    {
        fOut = new FileOutputStream(file);
    }
    catch (IOException e)
    {

    }
    try{
        fOut.write(byteWave); //THIS IS WARNING of POSSIBLE DE-REFERENCE 
        fOut.close();                                  //OF NULL POINTER
       }
         catch (IOException e)
             {

             }


    return mErr;
}
Run Code Online (Sandbox Code Playgroud)

Jea*_*art 5

如果抛出异常fOut即可null.因此编译器会警告您.

为了避免它,检查它不是null:

finally {
    if(fOut != null) {
        fOut.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

作为旁注:

  • 不要只是吞下异常(抓住他们什么都不做)
  • 把它close放在finally块中以确保它被执行
  • fOut如果有异常,请不要写入

您还可以使用try-with-resources语句,该语句非常安全并且可以为您工作:

try(fOut = new FileOutputStream(file)) {
    fOut.write(byteWave);
} catch(IOException e) {
    // do something with e
}
Run Code Online (Sandbox Code Playgroud)