i would like to handle my exceptions in a way to warning the user about the errors that occured .
What i know is something like:
servlet.java private void registerUser(...){ ... try{ DAOUser daoUser = new DAOUser(); daoUser.insert(user); catch(HibernateException he){ ... } DAOUser.java public void insert(User user) throws HibernateException { ... }
This is the best approach ? If not, what would you suggest ?
Best regards, Valter Henrique.
Advertisement
Answer
An exception can be handled in different ways. In this case, it seems that the exception is resulting in a user notification or an error message.
Now, the example you have shown should not throw any exception of that sort, where you need to notify user. First, validate user input; second, don’t make the flow of your program using exceptions.
Well, there are exceptions where we need to notify the user with some message. That can be done in controller
, typically, using messages stored in property files.
You must know where to catch exception, where to throw it, and where to log. Here first thing I would like to suggest is not to do both, throw and log. If you think logging is appropriate, don’t throw it. If you think throwing is appropriate, then don’t log it. When you follow this way, you will automatically know which one you need to log and which one to throw. That doesn’t mean some exceptions would go away without logging. The method, which doesn’t throw that further, holds the responsibility to log that exception.
Another thing is to know where to use checked
exception and where to use runtime
. The methods which throw runtime exceptions are somewhat easier to use, per se. But that doesn’t essentially mean that you should always use runtime exceptions.
I hope you are getting my points.