I’m reading through the documentation here. This example is what I’m questioning:
The first kind of exception is the checked exception. These are
exceptional conditions that a well-written application should
anticipate and recover from. For example, suppose an application
prompts a user for an input file name, then opens the file by passing
the name to the constructor for java.io.FileReader. Normally, the user
provides the name of an existing, readable file, so the construction
of the FileReader object succeeds, and the execution of the
application proceeds normally. But sometimes the user supplies the
name of a nonexistent file, and the constructor throws
java.io.FileNotFoundException. A well-written program will catch this
exception and notify the user of the mistake, possibly prompting for a
corrected file name.
In PHP I would check to see if the file exists prior to accepting it as valid user input with something like:
if (file_exists($file)) {
//proceed
} else {
//throw error to user
}
Am I to understand from reading this that in Java you would just need to “assume” the file provided was valid, and use the exception handler to throw an error instead of just checking to see if it exists? Or is using an Exception a much cleaner/efficient way of checking to see if the file exists?
It can be done either way; which makes more sense depends on context–but however it’s implemented, checked exceptions must either be handled, or declared to be thrown. That may change what makes the most sense.
I tend to check for a file’s existence before trying to do anything with it. But exceptions are just that–(generally) intended for exceptional circumstances.
For example, my app checks to see if the file exists, and it does. Between then and using the file, something else comes along and deletes it. Now there’s an exceptional condition that my code must handle as gracefully as possible.