当前位置: 技术问答>java相关
爲何這樣?variable socket might not have been initialized --socket.close()
来源: 互联网 发布时间:2015-02-26
本文导语: C:jdkstudynetmyjava.java:37: variable socket might not have been initialized socket.close(); ^ 1 error Exit code: 1 There were errors --------------------- import java.net.*; import java.io.*; public class myjava { public String ip="10.84.0.3"; pu...
C:jdkstudynetmyjava.java:37: variable socket might not have been initialized
socket.close();
^
1 error
Exit code: 1
There were errors
---------------------
import java.net.*;
import java.io.*;
public class myjava
{
public String ip="10.84.0.3";
public int port=25;
String result;
public void setaddress(String IPS )
{
ip=IPS;
}
public String startping()
{
result=ip+":"+port+":open socket ok";
Socket socket;
try{
try{
try{
socket=new Socket(ip,port);
}
catch(UnknownHostException e1){
result="e1 unknown host";
}}
catch(IOException e2){
result="e2 unable to open socket!!";
}}
catch(NullPointerException e3){
result="e3 unable to open socket!!";
}
try{
socket.close();
}
catch(IOException e4){
result="e4 unable to close socket!!";
}
return result;
}
public static void main(String args[])
{
System.out.println("Starting App");
myjava aa=new myjava();
aa.startping();
System.out.println(aa.result);
}
}
--------------------
|
Socket socket;
改为
Socket socket = null;
改为
Socket socket = null;
|
because socket=new Socket(ip,port) may fail and throw exception, so socket is not initialized.
To your program, you should say:
if (socket != null)
{
socket.close();
}
To your program, you should say:
if (socket != null)
{
socket.close();
}