Samrat Sarkar
Samrat Sarkar

Reputation: 13

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.

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

Upvotes: 1

Views: 649

Answers (2)

Jeffrey
Jeffrey

Reputation: 44808

You declare out within the try block. This means that is out of scope as soon as you leave the try portion of your try-finally statement. 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.

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

or

try(PrintWriter out = ...) {
}

Upvotes: 3

eis
eis

Reputation: 53502

You need to define "out" outside try-block if you want to reference it in the finally block, something like

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

Upvotes: 10

Related Questions