`
cjm0000000
  • 浏览: 32142 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Java Exception学习

    博客分类:
  • JAVA
阅读更多

通过对Java Core的学习,对java exception有了新的认识,之前在处理异常的时候,会采用try...catch...finally这种形式:

public void connect2() {
		Socket client 	= null;
		PrintWriter out = null;
		Scanner scanner = null;
		try {
			client = new Socket("173.39.171.51", 12211);
			client.setSoTimeout(5000);
			out 	= new PrintWriter(client.getOutputStream());
			scanner = new Scanner(client.getInputStream());
			while (scanner.hasNextLine()) {
				System.out.println("Recive :" + scanner.nextLine());
				out.println("Hello.");
				TimeUnit.SECONDS.sleep(5);
			}
		} catch (IOException | InterruptedException e) {
			//TODO your biz
			e.printStackTrace();
		}finally{
			if(null != out)
				out.close();
			if(null != scanner)
				scanner.close();
			if(null != client)
				try {
					client.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

 

看了Java Core上面的讲解后,新的异常处理会采用下面的形式:

public void connect() {
		try {
			Socket client 	= null;
			PrintWriter out = null;
			Scanner scanner = null;
			try {
				client = new Socket();
				client.connect(new InetSocketAddress("173.39.171.51", 12211),5000);
				out 	= new PrintWriter(client.getOutputStream(), true);
				scanner = new Scanner(client.getInputStream());
				while (scanner.hasNextLine()) {
					System.out.println("Recive :" + scanner.nextLine());
					out.println("Hello.");
					TimeUnit.SECONDS.sleep(5);
				}
			} finally {
				if(null != out)
					out.close();
				if(null != scanner)
					scanner.close();
				if(null != client)
					client.close();
			}
		} catch (IOException | InterruptedException e) {
			//TODO your biz
			e.printStackTrace();
		}
	}

 

第二中种形式的代码风格看着更加简洁,职能也更加专一:里面的try...finally 处理资源关闭;外面的try...catch处理异常。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics