0

Having trouble compiling my java file and i think the problem lies here: Problem faced is that i have to include a filenotfoundexception. however, when i add it in, compiler gives me an error of "overridden method does not throw filenotfoundexception" Any idea on how to solve this?

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;
      }
   } 
}
2
  • What do you want to do if the file is not found? Commented Feb 17, 2015 at 3:09
  • Can you give us the complete error message, and show us this line the compiler is complaining about? Commented Feb 17, 2015 at 6:17

2 Answers 2

1

You have to handle the FileNotFoundException yourself using try/catch.

Try this ...

Scanner scanner = null;
    try {
        scanner = new Scanner(new File("flights.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
Sign up to request clarification or add additional context in comments.

1 Comment

"overridden method does not throw filenotfoundexception"
0

I'm not sure what exactly are you doing, but isn't the error quite self-explanatory? "overridden method does not throw filenotfoundexception" error will show if you are trying to catch something that is not being thrown by any code in your try clause.

try{
    callMethodThatDoesNotThrowAnException();

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

On the contrary, if you have a method that throws a FileNotFoundException, then you can catch it:

    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");
}

hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.