java effitive 中关于exception的问题

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

猜你喜欢

转载自my.oschina.net/u/264182/blog/612519