在coressponding try块中没有抛出异常

时间:2015-10-22 10:36:37

标签: java

我正在尝试执行下面的代码。但我得到编译时错误。我写了下面的代码来显示文件" myfile.txt"的内容。 但实际上没有文件" myfile.txt"。然后是异常" FileNotFound"应该在运行时抛出。但是下面的程序没有编译。

为什么我会收到编译时错误?

代码:

import java.io.*;
class rethrow {
    public static void main(String args[]) {
        rethrow rt = new rethrow();
        try {
            rt.m1();
        } catch (FileNotFoundException FNFE) {
            FNFE.printStackTrace();
        }
    }

    void m1() {
        try {
            FileInputStream fin = new FileInputStream("myfile.txt");
            System.out.println("file contents");
            int ch;
            while ((ch = fin.read()) != -1)
                System.out.println((char) ch);
            fin.close();
        } catch (FileNotFoundException FNFE) {
            FNFE.printStackTrace();
            throw FNFE;
        } catch (IOException IOE) {
            IOE.printStackTrace();
        }
    }
}

---------------------------`------------------- -------- OUT PUT:

rethrow.java:11: exception java.io.FileNotFoundException is never thrown in bod
y of corresponding try statement
catch(FileNotFoundException FNFE)
^

rethrow.java:30: unreported exception java.io.FileNotFoundException; must be ca
ught or declared to be thrown
throw FNFE;
^
2 errors

2 个答案:

答案 0 :(得分:2)

你必须在方法./configure && make 中添加throws子句:

m1

否则您的 void m1() throws FileNotFoundException { 方法中有无法访问的FileNotFoundException的阻止块,方法main中的未处理的异常类型FileNotFoundException

在更改中无需捕获m1中的异常。

答案 1 :(得分:0)

将您的方法声明为以下

void m1() throws FileNotFoundException
{
 try
 {
  FileInputStream fin=new FileInputStream("myfile.txt");
  System.out.println("file contents");
  int ch;
  while((ch=fin.read())!= -1)
  {
   System.out.println((char)ch);

  }
  fin.close();
 }
 catch(FileNotFoundException FNFE)
 {
   FNFE.printStackTrace();
   throw FNFE;
 }
 catch(IOException IOE)
 {
  IOE.printStackTrace();
 }
}
  

您应该声明您的方法向调用方法抛出的异常类型。

相关问题