简体   繁体   中英

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?

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.
Eg 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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM