【问题标题】:Compiling java program filenotfoundexception编译java程序文件notfoundexception
【发布时间】:2015-02-17 14:39:26
【问题描述】:

编译我的 java 文件时遇到问题,我认为问题出在此处: 面临的问题是我必须包含一个 filenotfoundexception。但是,当我添加它时,编译器给我一个错误“覆盖的方法不会抛出 filenotfoundexception”关于如何解决这个问题的任何想法?

public String getArrival(String flightNumber) {
   Scanner scanner = new Scanner(new File("flights.txt"));
   while(scanner.hasNextLine()){
      String s = scanner.nextLine();
      if(s.indexOf(flightNumber)!=-1){
         String city = s.split("-")[1];
         System.out.println("getArrival(): " + flightNumber + " ==>     Arrival city is " + city);
         return city;
      }
   } 
}

【问题讨论】:

  • 找不到文件怎么办?
  • 你能给我们完整的错误信息,并告诉我们编译器抱怨的这一行吗?

标签: java exception compilation filenotfoundexception


【解决方案1】:

您必须使用 try/catch 自己处理 FileNotFoundException。

试试这个...

Scanner scanner = null;
    try {
        scanner = new Scanner(new File("flights.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

【讨论】:

  • "被覆盖的方法不会抛出 filenotfoundexception"
【解决方案2】:

我不确定你到底在做什么,但是这个错误不是很明显吗? "overridden method does not throw filenotfoundexception" 错误将显示您是否正在尝试 catch 某些不会被您的 try 子句中的任何代码抛出的东西。

try{
    callMethodThatDoesNotThrowAnException();

} catch (FileNotFoundException e){
   // if your try clause does not throw any FileNotFoundException, 
   // then this clause will NEVER be executed. 
}

相反,如果你有一个抛出FileNotFoundException的方法,那么你可以捕捉它:

    try{
        callMethodThatThrowsFileNotFoundException ();

    } catch (FileNotFoundException e){
       // the exception thrown by the method will be caught here 
    }

private void callMethodThatThrowsFileNotFoundException() throws FileNotFoundException{
    throw new FileNotFoundException ("File not found");
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    相关资源
    最近更新 更多