Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I catch 'connection refused' exception in Java?

Tags:

java

sockets

I want to know how I can catch a 'connection refused' exception in Java when I am using socket. (which would happen when server is down or not responding.)

Below is how I have implemented so far.

    try {
        sockfd = new Socket(host.getHostName(),heart_port);
        sockfd.setReuseAddress(true);
        BufferedReader message = new BufferedReader(new InputStreamReader ( sockfd.getInputStream() ) );
        message.close();
        sockfd.close();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
like image 681
user482594 Avatar asked Jul 31 '11 07:07

user482594


1 Answers

Add ConnectException before IOException

catch (ConnectException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} 
like image 106
Deepankar Sarkar Avatar answered Oct 20 '22 01:10

Deepankar Sarkar