当我编译下面的代码时,它显示错误"找不到符号变量"但是如果我在 finally 块中注释代码,我就能成功编译。
请指教。
public static int writeFile (String p_file_path, String p_data) throws Exception
{
try {
FileWriter outFile = new FileWriter(p_file_path,true);
PrintWriter out = new PrintWriter(outFile);
out.println(p_data);
} catch (Exception e) {
} finally {
out.close();
}
return SUCCESS;
}
如果你想
在 finally 块中引用它,你需要在 try-block 之外定义 "out",类似于
PrintWriter out = null;
try
{
FileWriter outFile = new FileWriter(p_file_path,true);
out = new PrintWriter(outFile);
out.println(p_data);
}
finally
{
if (out != null)
out.close();
}
您在try
块中声明out
。这意味着一旦您离开try-finally
语句的try
部分,这超出了范围。您可以在 try
语句之外声明它并在 finally
块中执行空检查,也可以使用 Java 7 的 try-with-resources
语句。
PrintWriter out;
try {
out = ...
} finally {
if(out != null) {
out.close();
}
}
或
try(PrintWriter out = ...) {
}