Exception和IOException之間的使用區別
先看一段代碼.這段代碼來自《深入剖析tomcat》
1 public void await() { 2 // 創建ServerSocket對象 3 InetAddress add = null; 4 ServerSocket ss = null; 5 try { 6 add = InetAddress.getByName(LOCAL); 7 ss = new ServerSocket(port, blocklog, add); 8 } catch (IOException e) { 9 e.printStackTrace(); 10 } 11 // 如果URI是/SHUTDOWN說明需要關閉服務器 12 Socket s = null; 13 InputStream in = null; 14 OutputStream out = null; 15 // 進入循環,知道響應完成 16 while (!shutdown) { 17 try { 18 //接收socket並創建流 19 s = ss.accept();//只會在8080端口接收到一個HTTP請求的時候才返回 20 in = s.getInputStream(); 21 out = s.getOutputStream(); 22 // 創建Request對象並parse,獲取資源uri 23 Request request = new Request(in); 24 request.parse(); 25 // 創建Response對象並執行操作 26 Response response = new Response(out); 27 // 傳入Request對象,根據getUri()獲取uri地址並進行加載 28 response.setReqest(request); 29 response.sendStaticResource(); 30 // 關閉socket,同時輸入流和輸出流自動關閉 31 s.close(); 32 // 檢查返回的URI是否是服務器關閉命令 33 shutdown = request.getUri().equals(SHUTDOWN_COMMAND); 34 } catch (Exception e) { 35 e.printStackTrace(); 36 //出現異常就繼續重新接收 37 continue; 38 } 39 } 40 }
在這里用的是Exception而不是IOException,這里使用Exception是為了保證捕獲異常后可以繼續維持JVM的運行.如果Exception換成IOException后,一旦出現IO異常,便會捕獲停止運行.
下面是運行結果(Exception)
如果拋出的是IOException
明顯看出后者導致JVM停止