• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

help on closing streams

 
yoga nandiwardhana
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
help, i have this code:
public void sendMsg(String message){
HttpConnection c = null;
InputStream is = null;
OutputStream os = null;

try {
//open the connection, input and output streams
}
catch(IOException ioe){
System.out.println("error " + ioe);
}
finally{
if(is!= null) is.close();

if(os != null) os.close();

if(c != null) c.close();
}
}
problem is, when i build the suite, the build failed with the message "unreported exception java.io.IOException; must be caught or declared to be thrown" on each close() method.
what should i do?
thanks
 
Axel Janssen
Ranch Hand
Posts: 2166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what the error messages says
try this one:

.. or you might span the try catch from the line following finally.
the problem with checked exception is that they sometimes result in code a bit verbose.
If you look up method close() in api you'll find that it throws a IOException. You have to check that or define throws in the method header. To check it in the method body is much better, but sometimes a bit typing.
 
yoga nandiwardhana
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks, i'll try that one.
btw, even without the if(is!=null) line, only closing the streams in the finally, it still generate the same error..
i found out that most examples i read do it that way, and no error, but why is it a problem on my code?
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I stole this from Jonathan Knudsen's book.

You don't have to have your method throw an IOException. I think I had that for the display to show a nice message for any Error that occurs. I tend to throw exceptions all the way up to the GUI.
Hope that works for you.
Mark
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic