Catching some exceptions but ignoring others - why doesn't this work?

旧街凉风 提交于 2019-12-24 10:35:18

问题


I have something similar to this.

void func() {
  try {
    //socket disconnects in middle of ..parsing packet..
  } catch(Exception ex) {
   if(!ex.getMessage().toString().equals("timeout") || !ex.getMessage().toString().equals("Connection reset")) {
     debug("Exception (run): " + ex.getMessage());
     ex.printStackTrace();
  }
}

Why is it that when I get a connection reset exception or a timeout exception, it still goes inside the condition. I tried without toString and with no luck.


回答1:


You shouldn't catch all exceptions and then test the error message of the exception. Instead only catch those exceptions that you intend to handle - for example SocketTimeoutException.

catch (SocketTimeoutException ex)
{
    // Do something...
}

With your current code you may be catching some other type of exception that you weren't expecting. Currently you will just ignore this exception, not even logging it. This can make it very difficult to debug what is going on. If you have an exception that you can't handle you should either rethrow it or log it.

I want to catch all exceptions

If you really want to do that then you can write your code as follows:

catch (SocketTimeoutException ex)
{
    // Do something specific for SocketTimeoutException.
}
catch (Exception ex)
{
    // Do something for all other types of exception.
}

Regarding your specific error, you have written:

!a.equals(b) || !a.equals(c)

This expression always evaluates to true. What you meant was:

!a.equals(b) && !a.equals(c)

Or equivalently:

!(a.equals(b) || a.equals(c))

Note that by rewriting your code as I suggested above you completely avoid having to write this complicated boolean expression.




回答2:


It's really not safe to rely on exceptions messages to know what is the cause of your exception.

In your case you can try to catch more specific exceptions, such as SocketTimeoutException and the classic IOException :

void func() {
    try {
        //socket disconnects in middle of ..parsing packet..
    } catch(SocketTimeoutException ex) {
        //In case of Time out
    } catch(IOException ex){
        //For other IOExceptions
    }
}

Sources :

[Socket.connect()][3]

Even if you prefer to seek informations in exceptions messages, you shouldn't check if the message simply is equal to "timeout" but if the message contains "timeout"

[3]: http://download-llnw.oracle.com/javase/6/docs/api/java/net/Socket.html#connect(java.net.SocketAddress, int)



来源:https://stackoverflow.com/questions/3542659/catching-some-exceptions-but-ignoring-others-why-doesnt-this-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!