public FileInputStream(String name)
                throws FileNotFoundException
throws FileNotFoundException 为什么throws FileNotFoundException 要用try catch语句对啊,throws不是向上一级抛出异常吗?不过他不是runtime Exception 必须要捕获,不然会出错的。

解决方案 »

  1.   

    你应该是要问为什么在方法上面抛出了 FileNotFoundException 异常,但在方法体中还要用try catch吧,我的理解是在方法体中你还要抛出其它的异常,而你抛出 FileNotFoundException 只抛出了文件找不到这个异常,没有抛出其它的异常,如果你用public FileInputStream(String name) throws Exception那么在方法体中就不用再写try catch了。这里主要涉及到一个异常的范围(大小)的问题
      

  2.   

    import java.io.*;
    import java.io.FileNotFoundException;public class FileList {
    public static void main(String args[]) {
    int b = 0;
    int num = 0;
    FileInputStream fis = null;
    try {
     fis = new FileInputStream("D:/A/B.txt");

    } catch (FileNotFoundException e) {
    System.out.println("而文件不错");
    System.out.println(-1);
    }
    try {
    while((b = fis.read()) != 0) {
    System.out.print((char)b);
    num ++;
    }
    fis.close();
    } catch(IOException e) {
    System.out.println("而文件不错");
    System.out.println(-1);
    }finally {
    System.out.println("又成功了加油");
    System.out.println("输出了" + num + "个字符");
    }
    }
    }
    这个finally语句为什么执行不了啊?????
      

  3.   

    有运行呀,我把代码copy到我本机上,运行结果为(不想截图,就直接复制了结果):
    而文件不错
    -1
    又成功了加油
    输出了0个字符
      

  4.   

    while((b = fis.read()) != 0) {改为while((b = fis.read()) != -1) {read
    public int read()
             throws IOException
    Reads a byte of data from this input stream. This method blocks if no input is yet available. Specified by:
    read in class InputStream
    Returns:
    the next byte of data, or -1 if the end of the file is reached. 
    Throws: 
    IOException - if an I/O error occurs.
      

  5.   

    完全不懂你要问什么,你的代码中之所以要catch异常是因为你的方法体是没有异常抛出的,但是你方法体内部却是有异常的。所有才需要try catch。如果你的方法体声明成:
    public static void main(String args[])throws FileNotFoundException..这样就不用try catch了