public class FinallyReturn {
public static int readFileByByte() {
try {
DataInputStream dis = new DataInputStream(new FileInputStream(
"e:/dd.java"));
DataOutputStream dos = new DataOutputStream(new FileOutputStream(
"e:/ddcopy.java"));
int b = 0;
while ((b = dis.read()) != -1) {
dos.write(b);
}
dis.close();
dos.close();
} catch (FileNotFoundException e) {
System.out.println("找不到指定的源文件!");
e.printStackTrace();
} catch (IOException e) {
System.out.println("读写文件发生异常!"); } finally {
System.out.println("finally");
} return 0;
} public static void main(String[] args) {
int i = readFileByByte();
System.out.println(i);
}
}
当没有找到文件时,打印 :
找不到指定的源文件!
finally
0
知道finally会打印出来,为什么返回值0也会打印出来呢?不是发生异常后程序就中断了吗
代码就转到这下面去执行了
catch (Exception e) {。}
------------------------------
楼主的程序中不是有捕获异常吗?再加这个catch 有什么意义吗?
谢谢你的提醒,我把readFileByByte里的return 0改成了return 1仍然打印出来1,看来上面几位朋友说的很对,异常已经捕获,程序继续执行。
我原来的理解有误,只有当异常没有被捕获,发生异常才会导致程序中止。当然也只有runtime异常才可以不去捕获,非runtime异常不捕获编译就会出错。
catch (FileNotFoundException e) {
System.out.println("找不到指定的源文件!");
e.printStackTrace();
throw e;
} catch (IOException e) {
System.out.println("读写文件发生异常!");
throw e; }