【问题标题】:Java error: unreported exception ioexception must be caught or declared to be thrownJava 错误:未报告的异常 ioexception 必须被捕获或声明为抛出
【发布时间】:2016-01-10 23:49:23
【问题描述】:

我在这里找不到我的代码有什么问题

public class Library{

FileReader fr = new FileReader("D:\\Users\\Adi\\Documents\\NetBeansProjects\\Hw 7Jan-13Jan\\Date.txt");
BufferedReader br = new BufferedReader(fr);

public void add(Publication p){
    if(counter < publication.length){
        publication[counter++]=p;        
    }
}

public boolean remove(int id){
    Publication p=null;

    for(int i=0;i<counter;i++)
        if(publication[i].getId()==id){
            p=publication[i];

            for(int j=0;j<counter-1;j++)
                publication[j]=publication[j+1];
                publication[counter-1]=null;
                counter--;
        return true;        
        }

            return false;}

}

我尝试使用 try{} catch{} 但后来出现其他错误:class,interface or enum expected

任何帮助表示赞赏!谢谢

P.S:我是这个 IOException 的新手并尝试{} catch{} :)

【问题讨论】:

  • 看看你正在使用的FileReader构造函数——它声明它可以抛出IOException。你希望它如何传播?目前你对受检异常了解多少? (还不清楚为什么你有frbr 的这些字段,因为你不会在其他任何地方使用它们,请注意......)
  • 您的代码的某些方法会引发检查异常“IOException”。此异常必须通过方法头中的throws IOException 传递给调用者,或者使用try 和catch 捕获。您需要显式捕获像这样的 IOException try { ... } catch(IOException e) { ... }
  • 您是否将 FileReaderBufferedReader 实例化包装在 try-catch 块中
  • 是的,我尝试输入 public class Library throws IOException,然后我得到“预期的类、接口或枚举”..
  • 我稍后会使用 br,但现在我遇到了这些错误

标签: java compiler-errors try-catch bufferedreader


【解决方案1】:

问题可能是,您将 FileReader fr 定义为类变量。然后你会得到一个错误来处理/定义异常。当您为句柄异常定义 try-catch 时,会出现另一个问题,即“类型的非法开始”。为此,您需要定义/声明:

static{
    try {
        FileReader fr = new FileReader("D:\\Users\\Adi\\Documents\\NetBeansProjects\\Hw 7Jan-13Jan\\Date.txt");
    } catch (Exception e) {
    }
}

或在构造函数中分配 FileReader。

FileReader fr;

public Library(){
     try {
        fr = new FileReader("D:\\Users\\Adi\\Documents\\NetBeansProjects\\Hw 7Jan-13Jan\\Date.txt");
    } catch (Exception e) {
    }
     BufferedReader br = new BufferedReader(fr);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多