Pitfall - Returning null instead of throwing an exception
suggest changeSome Java programmers have a general aversion to throwing or propagating exceptions. This leads to code like the following:
public Reader getReader(String pathname) {
try {
return new BufferedReader(FileReader(pathname));
} catch (IOException ex) {
System.out.println("Open failed: " + ex.getMessage());
return null;
}
}
So what is the problem with that?
The problem is that the getReader is returning a null as a special value to indicate that the Reader could not be opened. Now the returned value needs to be tested to see if it is null before it is used. If the test is left out, the result will be a NullPointerException.
There are actually three problems here:
- The
IOExceptionwas caught too soon. - The structure of this code means that there is a risk of leaking a resource.
- A
nullwas used then returned because no “real”Readerwas available to return.
In fact, assuming that the exception did need to be caught early like this, there were a couple of alternatives to returning null:
- It would be possible to implement a
NullReaderclass; e.g. one where API’s operations behaves as if the reader was already at the “end of file” position. - With Java 8, it would be possible to declare
getReaderas returning anOptional<Reader>.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents