通过对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处理异常。