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