[英]Compiling java program filenotfoundexception
编译我的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;
}
}
}
您必须使用try / catch自己处理FileNotFoundException。
尝试这个 ...
Scanner scanner = null;
try {
scanner = new Scanner(new File("flights.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
我不确定您到底在做什么,但是错误不是很明显吗? 如果您尝试catch
try
子句中任何代码未抛出的内容,则会显示"overridden method does not throw filenotfoundexception"
错误。
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");
}
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.