在原文中做者推薦在拋出異常時候要儘可能細化到具體的某個異常以方便調試。然而在實際過程當中因爲引用第三方jar包等緣由,其包中拋出異常可能會隱含性的包含其餘異常,此種狀況下外層服務調用在try-catch 代碼中可能會引發問題,這類問題因爲不細心又不容易發現。
public static void decompress(String unzipPath, String zipFilePath) throws Exception { FileOutputStream fileOut = null; File file; File unzip = new File(unzipPath); InputStream inputStream = null; byte[] buffer = new byte[8192]; int count = 0; ZipFile zipFile = null; File createfile=new File(zipFilePath); if(!createfile.exists()||createfile.isFile()){ createfile.mkdir(); } try { zipFile = new ZipFile(zipFilePath,"GBK"); for (Enumeration<?> entries = zipFile.getEntries(); entries .hasMoreElements();) { ZipEntry entry = (ZipEntry) entries.nextElement(); String str = entry.getName().replace("\\", "/"); file = new File(unzip.getPath() + File.separator + str); if (entry.isDirectory()) { file.mkdirs(); } else { File parent = file.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } try { inputStream = zipFile.getInputStream(entry); fileOut = new FileOutputStream(file); while ((count = inputStream.read(buffer)) > 0) { fileOut.write(buffer, 0, count); } } finally { if (fileOut != null) { fileOut.close(); } if (inputStream != null) { inputStream.close(); } } } } } finally { if (inputStream != null) { inputStream.close(); } if (zipFile != null) { zipFile.close(); } if (fileOut != null) { fileOut.close(); } } }
這個類會拋出IOExcepition 而然因爲壓縮包的緣由程序會拋出一個運行時異常。這樣就沒法捕獲異常,從而引發程序邏輯上的問題。調試