简体   繁体   中英

Exception handling for socket exception

I need to do different things based on the kind of exception i catch, the following are the two methods i learnt that can be used:

Method1:

 try{
    ..
    ..
    }catch(SocketTimeoutExceptione){
     //do something
    }
    catch(RunTimeException e){
    //do something
    }

Method 2:

try{
}
catch(RunTimeException e){
if (e instanceof SocketTimeoutException) {
                 LOGGER.error(e);   

            }else {
                LOGGER.error(e);
                //do something
            }
}

I get the following exception which is a known connectivity issue: Exception thrown org.springframework.web.client.ResourceAccessException: I/O error on POST request for "test": Read timed out; nested exception is java.net.SocketTimeoutException: Read timed out

The method 1 is not feasibe as it will still enter the runtime exception block. In method 2 i cannot check if it is a instance of run runtime exception, as socket excpeption is not part of it. How do i handle it in this case

java.lang.Object
  java.lang.Throwable
    java.lang.Exception
      java.lang.RuntimeException
        org.springframework.core.NestedRuntimeException
          org.springframework.web.client.RestClientException
            org.springframework.web.client.ResourceAccessException

This is the exception class hierarchy. I think if you try to catch ResourceAccessException instead of SocketTimeoutException it will be okay. But when catch could not find the specific exception, if it can catch its super exception classes, it catches that, in your case it is RuntimeException .

Ref : https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/ResourceAccessException.html

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