自从我使用Java以来,我一直在使用Java,所以我觉得这很让人困惑,但我在'FileProcessor.java'文件中有一个'FileProcessor'类。我想在我的“Driver.java”文件中使用它,但我不断收到此错误:在不同的文件中处理FileNotFoundException
error: unreported exception FileNotFoundException; must be caught or declared to be thrown
我在Java的整个例外事情有点困惑,我想我处理得在我的FileProcessor.java文件中,但我不知道。
FileProcessor.java
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
public class FileProcessor{
/**
* Reads one line from file
* @param arg A file
* @return The line that is read
*/
public String readLineFromFile(File f) throws FileNotFoundException,
IOException{
BufferedReader br = null;
String line;
try{
br = new BufferedReader(new FileReader(f));
line = br.readLine();
return line;
}
catch(IOException e){
e.printStackTrace();
System.err.println("Read method failed");
throw new IOException();
}
catch(FileNotFoundException e1){
e1.getMessage();
System.err.println("File is not found");
throw new FileNotFoundException();
}
}
}
Driver.java
import java.io.File;
import java.io.FileNotFoundException;
public class Driver{
public static void main(String args[]){
File inFile = null;
if (0 < args.length){
inFile = new File(args[0]);
}
else{
System.err.println("No input file found");
System.exit(0);
}
FileProcessor fileProcessor = new FileProcessor();
String lineRead;
try{
lineRead = fileProcessor.readLineFromFile(inFile);
}
catch(FileNotFoundException e){
throw new FileNotFoundException();
}
}
}
为什么你要捕捉异常,只是为了直接在后面抛出一个新的(完全不相关的,没有帮助的信息)异常。你应该看看一些关于异常处理的教程。 “如果你不能处理它,那就不要” –