开发者

How to handle exceptions in Java Web Applications?

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:

s开发者_如何学JAVAervlet.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.


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.


Well the better way would be

  • First Isolate Service/DAO/Controller/View layers.
  • Throw exception from service , handle it in controller and act it accordingly.

Our servlet wiki page demonstrated error message stuff nicely

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜