我在Java中引发自定义异常时遇到问题。 具体来说,我想故意抛出FileNotFoundException以便测试称为fileExists()的方法。该方法测试文件(A)不存在,(b)不是普通文件还是(c)不可读。对于每种情况,它将打印不同的消息。 但是,运行以下代码时,main方法显示默认的FileNotFoundException消息,而不是fileExists方法中的消息。我很想听听有关原因的任何想法。 所有变量都已声明,但是我没有在此处包括所有声明。
public static void main (String[] args) throws Exception {
try {
inputFile = new File(INPUT_FILE); // this file does not exist
input = new Scanner(inputFile);
exists = fileExists(inputFile);
System.out.println("The file " + INPUT_FILE
+ " exists. Testing continues below.");
} catch (FileNotFoundException ex) {
System.err.println(ex.getMessage());
}
}
public static boolean fileExists(File file) throws FileNotFoundException {
boolean exists = false; // return value
String fileName = file.getName(); // for displaying file name as a String
if ( !(file.exists())) {
exists = false;
throw new FileNotFoundException("The file " + fileName + " does not exist.");
}
else if ( !(file.isFile())) {
exists = false;
throw new FileNotFoundException("The file " + fileName + " is not a normal file.");
}
else if ( !(file.canRead())) {
exists = false;
throw new FileNotFoundException("The file " + fileName + " is not readable.");
}
else {
exists = true;
}
return exists;
}
答案 0 :(得分:0)
首先,您可能要避免使用与现有Java类相同的类名,以避免混淆。
在您的main
方法中,您需要在使用创建Scanner
对象之前检查文件是否存在。
此外,也不需要所有exists = false
,因为代码会在此处停止,因此您将引发异常。
可能的解决方法如下:
public static boolean fileExists(File file) throws FileNotFoundException {
String fileName = file.getName(); // for displaying file name as a String
if (!(file.exists())) {
throw new FileNotFoundException("The file " + fileName + " does not exist.");
}
if (!(file.isFile())) {
throw new FileNotFoundException("The file " + fileName + " is not a normal file.");
}
if (!(file.canRead())) {
throw new FileNotFoundException("The file " + fileName + " is not readable.");
}
return true;
}
public static void main(String[] args) throws Exception {
String INPUT_FILE = "file.txt";
try {
File inputFile = new File(INPUT_FILE);
if (fileExists(inputFile)) {
Scanner input = new Scanner(inputFile);
System.out.println("The file " + INPUT_FILE + " exists. Testing continues below.");
}
} catch (FileNotFoundException ex) {
System.err.println(ex.getMessage());
}
}
答案 1 :(得分:0)
您还可以选择创建一个类,在其中扩展FileNotFoundException,将其作为文件作为文件,然后将其放入catch中,并继续覆盖该类中的打印输出。