在原文中做者推荐在抛出异常时候要尽可能细化到具体的某个异常以方便调试。然而在实际过程当中因为引用第三方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 而然因为压缩包的缘由程序会抛出一个运行时异常。这样就没法捕获异常,从而引发程序逻辑上的问题。调试