I'm having a problem with custom exception throwing in Java. Specifically, I'd like to intentionally throw a FileNotFoundException in order to test a method called fileExists(). The method tests if the file (A) doesn't exist, (b) is not a normal file, or (c) is not readable. It prints a different message for each situation. However, when running the following code, the main method displays the default FileNotFoundException message, rather than one in the fileExists method. I'd love to hear any thoughts as to why. All variables were declared, but I did not include all of the declarations here.
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;
}
First of all you might want to avoid using same class names as existing Java classes so as to avoid the confusion.
In your main
method, you would want to check if the file exists before you use create the Scanner
object.
Also, there is no need for all the exists = false
where you will be throwing an exception as the code stops there.
A possible solution will be as follows:
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());
}
}