• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

return to sender

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic