Throw exceptions: don’t return null

Tuesday, 30 March 2004

If a function that returns an object is unable to return the object because of an error, it should not return null. Instead, it should throw some defined exception. This means that the handling for the error can occur at the appropriate place, by catching the defined exception. This appropriate place may be at the point of the function call, or somewhere further up the call stack.

If the function returns null instead, then that forces error handling to happen where the call is made, by testing for a null pointer. If this is not done, a null pointer exception is the likely result, and this won’t (or shouldn’t) be caught at all.


Leave a comment