Questions about exceptions in java effitive

在原文中作者推荐在抛出异常时候要尽量细化到具体的某个异常以方便调试。然而在实际过程中由于引用第三方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();
			}
			
		}

	}

This class will throw an IOException and the program will throw a runtime exception due to the tarball. In this way, the exception cannot be caught, causing problems in the program logic.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325462609&siteId=291194637