Win a copy of Java Database Connections & Transactions (e-book only) this week in the JDBC forum!
  • 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
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

return to sender  RSS feed

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello happy new year and thankyou for reading this
i am experimenting with io at the moment and came across the following puzzle
why in the code below do I have to include the
return;
at the end of the try/catch statement for the file to compile without the
fin might not be initialized error

import java.io.*;

class CopyFile {
public static void main(String args[]) throws IOException {
int i;
int a=args.length;
int b;
int c=54;
FileInputStream fin;
FileOutputStream fout;
try {fin=new FileInputStream(args[0]); } catch (FileNotFoundException e) { System.out.println("filenferror"); return;}
try {
i=fin.read();
} catch (IOException e) { System.out.println("fileerror");
}
fin.close();
}
}
 
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Happy New Year to you, too.
What happens if the "new FileInputStream" throws an exception? Answer: execution jumps immediately to the catch block - without even doing the assignment to 'fin'.
So, if you didn't have the 'return', the code would exit the catch block and move onto to "fin.read()" - But in this case, 'fin' is still unassigned !!
To avoid this situation, Java insists that all variables are "definitely assigned" before use - and will throw the compiler error you hit if there is even the possibility of unassigned variable usage.
 
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simcel,
Rob is absolutely right in his reply. That's a nice feature about JAVA. The compiler checks all local variable must be initialized before you're allowed to use it. A better way to structure your program is:


There's nothing to say that you can't imbed try...catch blocks.
-Peter
 
Enjoy the full beauty of the english language. Embedded in this tiny ad:
how do I do my own kindle-like thing - without amazon
https://coderanch.com/t/711421/engineering/kindle-amazon
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!