• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Himai Minh
  • Carey Brown
  • salvin francis

strange error

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi folks,
I was in the mid of compiling a program and it was giving error which is as:
fileprint.java:26: Variable fin may not have been initialized.
i = fin.read();
^
To my surprise when i added return; statement just before end of exception it was not giving error.
Please explain me on this.
The program is as
import java.io.*;
class fileprint{
public static void main( String args[] )
throws IOException
{
int i ;
FileInputStreamfin;
try {
fin = new FileInputStream(args[0]);
} catch ( FileNotFoundException e ) {
System.out.println(" File Not Found ");
}
do {
i = fin.read();
if( i != -1 ) System.out.print( (char) i);
} while(i != -1);
fin.close();
}
}
 
mister krabs
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Method variables are not initialized therefore fin doesn't have a value set until it hits the try...catch statemnt. However, if the try...catch throws an exception, fin will still not be initialized and the flow will go to the next statement after the try...catch. So it can hit the fin.read() without ever having been initialized. If you add the return statement to the catch, then it won't ever reach the fin.read() without having initialized fin.
 
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The usual solution to this sort of problem is to put all your
code which do file io into the try/catch so your example would become:
 
Thomas Paul
mister krabs
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The other possibility is to simply initialize fin.
FileInputStream fin = null;
That will get you past the compile error. then just check that fin isn't still null before you use it.
 
You'll never get away with this you overconfident blob! The most you will ever get is this tiny ad:
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic