import java.io.*;
public class Mine {  
    public static void main(String argv[]){
        Mine m=new Mine();
        System.out.println(m.amethod());  
    }   
    public int amethod() {
        try {   
            FileInputStream dis=new FileInputStream("Hello.txt");
        }catch (FileNotFoundException fne) {
            System.out.println("No such file found");
            return -1;
        }catch(IOException ioe) {
        } finally{   
            System.out.println("Doing finally");
        }
        return 0;  
    }
}
if you try to compile and run the following code, but there is 
no file called Hello.txt in the current directory?. Answer is::
No such file found, Doing finally, -1 
why not:::No such file found, Doing finally, 0why?

解决方案 »

  1.   

    finally语句一定得在return语句之前执行,所以执行顺序应该是1):打印no such file;2):执行finally语句里面的内容;3):返回-1;如果把return 0语句写到finally语句里面,会返回0的。
      

  2.   

    FileInputStream dis=new FileInputStream("Hello.txt");
    >this will cause FileNotFoundException, and this is first caught by
    }catch (FileNotFoundException fne) {
    >and print "No such file found" to the console.
    >becasue the is a return after the print the message, it should return immediately, >but the is a finally, it will execute the finally and then return. i.e.
    System.out.println("Doing finally");
    return -1;so the output should be:
    No such file found
    Doing finally
    -1
      

  3.   

    因为java的异常处理机制是无论如何都要执行finally,
    在这个例子中,在执行到System.out.println("No such file found"); return -1;并不是立刻return,而且在return之前先执行finally,输入System.out.println("Doing finally");然后再return -1.
      

  4.   

    return 0; 写到finally里面会返回0