Re: Exception handling and snarky compiler
On 27-8-2008 16:00, Tom A. wrote:
I am trying to set up a random access file RanFile.
(sorry, I don't have my code with me)
I have confirmed or created the directory, I have confirmed or created
the file in a File object, and then I create the random file
try { RanFile = new RandomAccessFile(File, "rw" ); }
catch ( < exceptions> ),
{ < put out informative error, and exit program > }
Then I use RanFile
RanFile.seek(0L);
and the compiler complains that RanFile may not be initialized. Now I
know that if it wasn't, then the program would have ended by this
point. How do I convince the compiler of that?
Thanks.
Tom A.
I assume you are using System.exit(status) to exit the program.
To the compiler calling the System.exit method is just like calling any
other method: it expects a normal return from the call. The compiler
doesn't (have to) know that a call to the System.exit method will not
return normally but terminates the JVM -- in most cases that is:
System.exit might throw a SecurityException if your code runs with a
security manager in place which doesn't allow your code to exit the JVM.
So the compiler finds that there is an execution path (out of the catch
block) in which the RanFile variable wasn't initialized.
To get rid of the error, initialize the variable with null at its
declaration ( /*A*/ in the example code below). This is the best
solution IMO. Alternative 1 is assign null to the variable after the
System.exit call (). The second alternative is to put a return statement
there ( /*B*/ ).
public void process(String fileName) {
RandomAccessFile file /*A*/;
try {
file = new RandomAccessFile(fileName, "r");
} catch (FileNotFoundException ex) {
System.out.println("Couldn't open " + fileName);
System.exit(1);
/*B*/
}
// Error on the line below: "The local variable
// 'file' may not have been initialized"
file.seek(0);
// and other stuff
}
--
Regards,
Roland