如何在 Java 中捕获“连接被拒绝”异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6888139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:45:42 来源:igfitidea点击:
How do I catch 'connection refused' exception in Java?
提问by user482594
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.)
我想知道在使用套接字时如何在 Java 中捕获“连接被拒绝”异常。(当服务器关闭或没有响应时会发生这种情况。)
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();
}
回答by Deepankar Sarkar
Add ConnectExceptionbefore IOException
在IOException之前添加ConnectException
catch (ConnectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}