Link to home
Start Free TrialLog in
Avatar of sigma19
sigma19Flag for United States of America

asked on

java exception during file operation

try
{
FileWriter fstream = new FileWriter(filename);
BufferedWriter out = new BufferedWriter(fstream);      

so some processing on out.
out.close();                                                         
}

catch (Exception ex)
{
out.close();
}                     

===
I want to open a file and do some processing.
I want to close the file once everything is done.

If there is any exception
I am ccatching them but not able to close the file.
so when I keep the above code in catch, it gives cannot find symbol.

so when I keep the "out" decalartion outside try
 unreported exception java.io.IOException; must be caught or declared to be thrown
   FileWriter fstream = new FileWriter(filename);

can you correct me?
Avatar of for_yan
for_yan
Flag of United States of America image

Why you close it twice?
Avatar of Mick Barry
BufferedWriter out = null;
try
{
FileWriter fstream = new FileWriter(filename);
out = new BufferedWriter(fstream);      

so some processing on out.
out.close();                                                        
}

catch (Exception ex)
{
if (out!=null) out.close();
}                    

"when I keep the above code in catch, it gives cannot find symbol" - strange - please post the bigger piece of code
or use a finally block


BufferedWriter out = null;
try
{
FileWriter fstream = new FileWriter(filename);
out = new BufferedWriter(fstream);      

so some processing on out.
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (out!=null) out.close();
}                    
Avatar of sigma19

ASKER

Objects, the code you gave is not working as it gives
 unreported exception java.io.IOException; must be caught or declared to be thrown

Is this about this RSS ffeds program?
Works for me already  for several days without any problems.

Keep them all in one try catch
loop, and don't catch IOException,
catch just Exception and you'll have no problems
with any of that.



Avatar of sigma19

ASKER

nope this is for general file operations.

I have only one exception I dont catchIOExceptions.

the flow is same as what objects: mentioned.
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Well, if you want to be rigoristic, use finally.
All my life I open and close files and live without finally quite well