Search code examples
javadao

What is the best layer to handle a NullPointerException?


My system has these classes:

PersonBean - handles the requests from the view;
PersonService - provides all operations for the PersonBeam;
PersonDao - provides data access from db to Service classes;

I have a findById(int personId) method on my PersonDao class. When PersonDao cannot find any Person with the provided Id it returns Null. Where should I handle the Null? In which layer?


Solution

  • I would say that the null should be passed back as far as possible in the stack, so that it can be handled at each layer differently if needed (and depending on the path to the PersonDao, if it differs in other areas of the code). In this case I think it would make sense to handle the null in PersonBean.

    This is all assuming that you're only talking about a null reference, not a NullPointerException, if that was the case, handle it at the lowest level, which would be the PersonDao.