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也会打印出来呢?不是发生异常后程序就中断了吗

解决方案 »

  1.   

    虽然发生了异常, 但这个异常被你这行代码catch了, } catch (FileNotFoundException e) {
    代码就转到这下面去执行了
      

  2.   

    try  catch 存在的意义就在于对异常进行处理, 防止程序中断。
      

  3.   

    明白了,原来发生异常后程序就中断的情况是因为   没有捕获异常,如RuntimeException。
      

  4.   

    加:
    catch (Exception e) {。} 
      

  5.   


    ------------------------------
    楼主的程序中不是有捕获异常吗?再加这个catch 有什么意义吗?
      

  6.   

    "不是发生异常后程序就中断了吗"   非也    因为异常被你捕获了(虽然你没处理 只是加了个输出)  如果你在catch块中 throw 出个异常  就不会输出0了
      

  7.   

    有捕捉除了IOException之外的exception意义.
      

  8.   


    谢谢你的提醒,我把readFileByByte里的return 0改成了return 1仍然打印出来1,看来上面几位朋友说的很对,异常已经捕获,程序继续执行。
    我原来的理解有误,只有当异常没有被捕获,发生异常才会导致程序中止。当然也只有runtime异常才可以不去捕获,非runtime异常不捕获编译就会出错。
      

  9.   

    finally 在任何时候都会执行到的
      

  10.   

    捕捉异常后做异常处理了,程序不会停止,继续执行。如果在catch程序块儿中,想做一些处理后停止处理,那把该异常再抛出即可。public static int readFileByByte() throws FileNotFoundException, IOException
     catch (FileNotFoundException e) {
                System.out.println("找不到指定的源文件!");
                e.printStackTrace();
                throw e;
            } catch (IOException e) {
                System.out.println("读写文件发生异常!");
                throw e;        }