Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

problem with IO Exception  RSS feed

 
Ranganath Junpal
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i am facing a some simple and wierd issue here.. may be because of my ignorance.

I have method like this:-
------------------------------------------------------------------------
public List<File> getSupportInfoFile()
throws IOException
{
FileWriter obj=null;
BufferedWriter obj1=null;
try
{
obj=new FileWriter("myFile.txt");
obj1= new BufferedWriter(obj);
}
catch(IOEXception exception)
{
exception.printStackTrace();
}
finally
{
// here it shows as error saying that IOEXCeption needs to be caught.
obj1.close();
}
}

-------------------------------------------------------------
In above piece of code :-
1) Is it mandatory to use throws IOException even though the code is in try,catch {} block as above? i feel its a bad way of programming. can some one let me know whts wrong above?

2)why in finally block{} obj1 shows as error saying that the IOException is not caught?

Thank you
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a try/catch/finally block the exceptions are captured in the try block, then the catch block is called and then the finally.

However, if other exceptions happen in the catch or finally block you will need another try/catch block to capture them. That is the case in your code since the close() method of the stream produces IOException, and this time in the finally block, therefore, outside the domain of the catch block.

You could do this:



For instance, in the Jakarta IO Commons Framework there is method named closeQUietly() that closes an InputStream and silently ignore whatever exception it produces.
[ January 20, 2007: Message edited by: Edwin Dalorzo ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!