写法1:
try {
         while(connect) {                       //控制循环结束,初始为true
String str = dis.readUTF();
System.out.println(str);
}
}catch (EOFException e) {
System.out.println("客户端断开连接");
} catch (IOException e) {
System.out.println("接收错误");
e.printStackTrace();
} finally {
stop();                              //将connect值设为false,并且关闭流和套接字
}
写法2:
while(connect) {
try {
                  String str = dis.readUTF();
System.out.println(str);
}
catch (EOFException e) {
System.out.println("客户端断开连接");
} catch (IOException e) {
System.out.println("接收错误");
e.printStackTrace();
} finally {
stop();
}
}请问这两种写法为什么执行效果完全不一样,第一种就会得到正确的结果,而第二种的String str = dis.readUTF();这句话
就会抛出DataInputStream.readUTF(Unknown Source)的异常?
先谢谢大家啦

解决方案 »

  1.   

    while(connect) {
    try {
    String str = dis.readUTF();
    System.out.println(str);
    }
    catch (EOFException e) {
    System.out.println("客户端断开连接");
    } catch (IOException e) {
    System.out.println("接收错误");
    e.printStackTrace();
    } finally {
    stop();
    }
    }
    一次循环你就stop了,stop是不是把io关了?
      

  2.   

    第一个while是在try内,也就是说当真的时候一直会循环while里面的内容。
    第二个while是包含try的,也就是说执行了一次之后,就跑到finally去了,也就stop了,然后也就宣告结束了。
      

  3.   

    第二种写法,循环体里面finally里面的close方法,应该是将IO流或者Socket关闭了。
    后面的循环,在进行读操作,肯定会抛出异常。