0

I use DAO's to acces my database, and those dao methods throw SQL Exception, so i make it so that dao methods throw this exception.

Then i acces DAO's through Services, to it looks like:

public class UserService implements Service {

    public int addNewUser(String username, String password) throws SQLException {
        User user = new User(username, password);
        UserDao dao = new UserDao(source.getConnection());
        return dao.add(user);
    }
}

Those methods throw exception too, but this way i have to handle SQL Exception in many places and sometimes it looks quite bad. Should i handle exception in service or dao? Or is it ok to check for an exception everywhere?

Sangram Badi
  • 4,054
  • 9
  • 45
  • 78
EmberTraveller
  • 355
  • 3
  • 18
  • 1
    depends. are you the only one to use the library? do you want the same error handling for all applications using it? ... What if someone else uses it, wants specific error messages on the ui and you handle everything in the back-end .. it all depends on what you try to achieve – Stultuske Sep 25 '17 at 09:04
  • 1
    throw it as far as needed so that the the user will be displayed with an error message so he knows something is wrong. also you should try to separate GUI and business logic – XtremeBaumer Sep 25 '17 at 09:04

1 Answers1

2

This can get quite subjective. Where should you handle your exceptions? It's up to you, there's no rule. My advice: keep throwing the exception upward until you get to the place where you want to log it. If you want to display a "Something went wrong with the database access"-message to the end user, it is easiest to have a "throws SQLException" in all lower-layer method headers, and only have a try-catch at the highest level.

Btw, you state you "handle" the SQL exception "in many places", but throwing the exception upward isn't usually called handling. Only the part that uses try-catch "handles" the exception, which, following my advice, would be the highest layer you have.

Edit: as this answer states, you might want to try-catch it in you DAO, and throw a different (more generic) exception upward, because the higher layers don't necessarily have a use for all those database-specific details. That would be an even fancier way to do it, although it might be overkill, depending on your situation.

Overleaf
  • 710
  • 6
  • 10
  • 1
    Exactly what I'd recommend. One more clarification: the only situation where a method is allowed to return normally (without exception) is if it completely fulfilled its job. Otherwise it has to tell its caller about the failure: throw an exception or let an existing exception ripple through. – Ralf Kleberhoff Sep 25 '17 at 09:55