捕获异常的顺序问题

 

在做小程序练习的时候,设置BindException异常,在此处老是提示错误(已经引入包java.net.BindException),如下图所示:

 

最终的解决方法是将此异常处理中的BindException异常与IOException异常互换位置,即先捕获BindException异常,然后捕获IOException异常。

 

附修改后可正常运行的代码:

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {
	static boolean isStarted = false;
	static ServerSocket ss = null;
	static Socket s = null;
	static DataInputStream dis = null;

	public static void main(String[] args) {
		try {
			ss = new ServerSocket(8888);
		} catch (BindException e) {
			System.out.println("端口使用中....");
			System.out.println("请关掉相关程序并重新运行!");
			System.exit(0);
		} catch (IOException e) {
			e.printStackTrace();
		}

 /*以上异常处理,BindException异常与IOException异常顺序颠倒会导致程序报错*/

		try {
			isStarted = true;
			while (isStarted) {
				boolean isConnected = false;
				s = ss.accept();
				isConnected = true;
				System.out.println("success connected");
				dis = new DataInputStream(s.getInputStream());
				while (isConnected) {
					String str = dis.readUTF();
					System.out.println(str);
				}
			}
			// dis.close();

		} catch (EOFException e) {
			System.out.println("client is closed!");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (dis != null)
					dis.close();
				if (s != null)
					s.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

}

 

posted @ 2010-09-19 23:12  Mr.chenz  阅读(665)  评论(0编辑  收藏  举报