简体   繁体   English

最终阻止在Oracle的JAVA存储过程中无法正常工作

[英]Finally block not working in JAVA Stored procedure for Oracle

When I compile the below code, it shows error "cannot find symbol variable out" But if i comment the code in the finally block, I am able to compile successfully. 当我编译下面的代码时,它显示错误“找不到符号变量”,但是如果我在finally块中注释了代码,则能够成功编译。

Please advise. 请指教。

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;
}

You need to define "out" outside try-block if you want to reference it in the finally block, something like 如果要在finally块中引用它,则需要在try块之外定义“输出”

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();
}

You declare out within the try block. 您声明out的中try块。 This means that is out of scope as soon as you leave the try portion of your try-finally statement. 这意味着,一旦您离开try-finally语句的try部分,就超出了范围。 You can either declare it outside of your try statement and do a null check in your finally block, or use Java 7's try-with-resources statement. 您可以在try语句之外声明它,并在finally块中进行空检查,或者使用Java 7的try-with-resources语句。

PrintWriter out;
try {
    out = ...
} finally {
    if(out != null) {
        out.close();
    }
}

or 要么

try(PrintWriter out = ...) {
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM