2

I am catching generic exception in the DAO class and wraps it to a DaoException. The main reason for doing this is, EBean is throwing different Runtime exceptions in case of failure to save, that I dont want to propagate them to upper layers. Upper layers should only know whether the saving is successful or not.

Following is the code snippet.

   public void save(Object object) throws DaoException {
        try {
            Ebean.save(object);
        } catch (Exception e) {
            throw new DaoException("Error saving record", e);
        }
    }

This goes against the general conception that generic exception should not be caught.

But is this acceptable in this scenario or still a bad practice?

Few more things to add to my question. My exact requirement is

  1. There is set of independent objects that I need to persist with in transaction. ( Need to do this in a transaction to avoid other instance making changes to the same object at same time)

  2. In case one object fails to persits due to some error, still other objects need to persist. (Cz they are independent)

What I am doing in service layer is looping the set of objects. If I receive a DaoException from one object I add that to error response and still continue the loop. But it should not break the transaction. Is there any better way of achiving this requirement?

nuwan
  • 90
  • 7

1 Answers1

1

In Exception handling, the thumb rule to follow is : Catch early, handle later.

In Dao layer, if you want to take any action when any specific type of Excepion occurs, then you must catch the specific exception rather than generic Exception class.

E.g : When using spring jdbc, we can catch various type of exceptions and accordingly we can take actions, like perform a retry of that database operation or wait for some time for any lock to be acquired.

However, if you don't need any processing in Dao layer in case of exception situations, then you better to handle that exception in the outer classes.

Shailesh Pratapwar
  • 4,054
  • 3
  • 35
  • 46