Hi,
When should one use exceptions and when should one just return null/false?
My virtual filesystem will return exceptions when trying to open a file
that is not readable or does not exist.
Should I not just return false when trying to open a nonexistent file?
Exceptions are a good thing to make something fail-fast. When an error
occurs and there is no way to handle that in a proper way and to
continue as if the error did not occur, then an exception is the best
way to propagate this error.
If a File.getOutputStream() returns null rather than throwing an
Exception, if the File can not be written, then it is easy for the
programmer to ignore the possibility of such error:
File f=new File(...);
FileOutputStream out=f.getOutputStream();
f.write(datasource.getSomeObject());
This example-code (and nearly every other code) will fail sooner or
later - in this case by throwing a NullPointerException in the third
line. But it is much better when the code fails fast instead of ignoring
the error and fail later, because when the the code fails early, the
error can be found, interpreted and resolved much better.
For example: If the user gets an error-message "NullPointerException in
line x" he must call the support to find out what went wrong. The
support perhaps thinks that "datasource" is null and is even more confused.
Whereas, when there would be a "FilePermissionException", the programmer
*has* to catch it (if it is a checked exception) and normally, he would
write an errormessage like "You are not allowed to write to that file"
instead of some cryptic "NullPointerException".
Even worse if the code does not produce a NPE, but an incorrect result
which seems to be valid at first glance!
Ciao,
Ingo