异常处理,出现异常不可忽略。
问题描述
finally中异常覆盖了catch到的异常:
public void show() throws BaseException {
try {
Integer.parseInt("Hello");
} catch (NumberFormatException e1) {
throw new BaseException(e1);
} finally {
try {
int result = 2 / 0;
} catch (ArithmeticException e2) {
throw new BaseException(e2);
}
}
}
原因分析:
很明显,当catch到异常之后,还会继续执行finally块代码,由于Java只有一张异常表,所以最后finally块中如果抛出异常,就会覆盖前面所有的异常。
为此,Java7开始,特意在Throwable中增加了一个方法,来解决这个问题:
public final void addSuppressed(Throwable exception)
public void read(String filename) throws IOException {
FileInputStream input = null;
IOException readException = null;
try {
input = new FileInputStream(filename);
} catch (IOException ex) {
readException = ex;
} finally {
if(input != null){
try {
input.close();
} catch (IOException ex2) {
if(readException != null){
readException.addSuppressed(ex2); //注意这里
}else{
readException = ex2;
}
}
}
if(readException != null){
throw readException;
}
}
}
解决方案:
Java7已经考虑到了,用就好了。而且,Java7 开始提供的 try-with-resource 异常代码块(语法糖),就用到了该特性:
package com.mocha.lambda;
import java.io.*;
import java.util.zip.GZIPOutputStream;
public class TryResourceTest {
public static void main(String[] args) {
try (FileInputStream fin = new FileInputStream(new File("input.txt"));
FileOutputStream fout = new FileOutputStream(new File("out.txt"));
GZIPOutputStream out = new GZIPOutputStream(fout)) {
byte[] buffer = new byte[4096];
int read;
while ((read = fin.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
} catch (IOException e) {
//异常处理 TODO
}
}
}



