代码如下:
DatagramSocket socket;
try{
socket=new DatagramSocket(port);
}
catch(SocketException e){
System.out.println("Failed to define DatagramSocket object.");
}
...
socket.send(packet);
编译提示:
variable socket might not have been initialized
^
我把try catch块去掉,编译提示:
unreported exception java.net.SocketException; must be caught or declared to be thrown
socket=new DatagramSocket(port);
^
1 error
不知如何才能解决?
------解决方案--------------------
DatagramSocket socket = null;
------解决方案--------------------
- Java code
DatagramSocket socket = null;try{ socket=new DatagramSocket(port); } catch(SocketException e){ System.out.println( "Failed to define DatagramSocket object. "); } ... socket.send(packet);
------解决方案--------------------
如果你的程序中try{}catch{}抛出异常的话,那么socket将不能被初始化,而你在socket.send(packet)中用到了这个没有初始化的变量所以楼上的是正解