What to do with exceptions in java?

I am beginner in Java programming. But i have code below

  Socket socket = serverSocketObj.accept();
  BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
  try {
    writer.writeLine();
  } catch(IOException e ) {
    //write to logger here
  } finally {
    writer.close(); // this throws IOExceptioin too. What to do with it
    // Possible memmory leak?
    socket.close();
  }

When i try to close writer i should handle another Exception. But i don't know what to do with it. Is this Exception impossible in my case? Can i just ignore it?

Answers


If you don't know what to do with them, just catch them and log them. The simplest way of logging them is e.printStackTrace() This way, at least you'll always see there's a problem if an exception occurs.

Another approach is to just re-throw the exceptions to upper-level code. E.g. if your method (in which your sample code is) declares to throw IOException, then there's nothing you should worry about. Let upper-level code worry about it.


Just check if the writer and socket are not null.

 Socket socket = serverSocketObj.accept();
  BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
try {     
    writer.writeLine();
  } catch(IOException e ) {
    //write to logger here
  } finally {
    if(writer != null)
    writer.close(); // this throws IOExceptioin too. What to do with it
    // Possible memmory leak?
    if(socket != null)
    socket.close();
  }

Unfortunately, to make the compiler happy you must catch the potential IOExceptions from the close statements (assuming you don't add IOException to your method's throws clause). (Thank you Mr Goodenough!)

But there's nothing you can really do to "handle" the exception once you have it, other than to log it.

(I'm thinking that the new "try with resources" structure in Java may handle this all a bit cleaner.)


Need Your Help

FM in Android application in eclipse

android eclipse

I have got a problem in FM application.

Element not found in the cache - perhaps the page has changed since it was looked up -why?

java selenium

I am new in this field and I would like to ask how can i loop if I am trying to achieve this scenario: (JAVA CODE THAT INVOLVES SELENIUM AND WEBDRIVER)