I am coming back to writing code in Java after a long gap - most of my coding work over the past few years has been in PHP & JavaScript - and am discovering that I have to work harder to satisfy the Java compiler which is far more rigorous about issues such as variable scope and exception handling. A piece of code that caused me some trouble is shown below
File file = new File(path, fname);
FileOutputStream stream = null;
try
{
stream = new FileOutputStream(file);
stream.write(tosave.getBytes());
}
finally
{
try
{
if (null != stream) {stream.close();}
return true;
}
catch(Exception e){return false;}
}
This is accepted by the compiler. However, before I got here I had run into several issues.
- First attempt: No Catch Block. The compiler refused to play ball because it wanted me to deal with the eventuality that the FileOutputStream could not be created. Ditto for writing to that stream. I understand the logic behind this reasoning and like it.
- Second attempt: Catch Block but...:I was declaring and creating the
stream
variable INSIDE thetry
block. The compiler threw a wobbly again - thestream
variable was out-of-scope in thefinally
block.
As you will see I have gotten around the issue by declaring stream
above the try
block and initializing it to null.
This works. However, given just how rusty my Java skills are I thought I would ask: Is there a right way to write such code?