Discussions

General J2EE: Exceptions handling

  1. Exceptions handling (3 messages)

    I build a DAO method to get Location object by an id:
    public Location getLocationById( int locationId );

    I will only call this method when there should be a Location having same id as locationId. So if I could not find that Location for any reason its an error. So I change my DAO method :
    public Location getLocationById( int locationId ) throws LocationNotFoundException;

    Now couple of other things can go wrong in this method like connection errors, resultset errors, etc. Most of them are catched by SQLException. I dont want to throw LocationNotFoundException in such case as this is not true. What should i do?

    Thanks

    Threaded Messages (3)

  2. Exceptions handling[ Go to top ]

    you can always throw one or more exceptions i a method

    public Location getLocationById( int locationId ) throws LocationNotFoundException,SQLException
  3. SQLErrorCodesTranslator[ Go to top ]

    To handle SQLException, the best way is to use a SQLErrorCodesTranslator, which will help you transalte the sql error code to the specific exception class. you can refer to the SQLErrorCodesTranslator of spring framework, it is pretty good.

    public class SQLErrorCodesTranslator extends SQLErrorCodeSQLExceptionTranslator {
    protected DataAccessException customTranslate(String task, String sql,
    SQLException sqlex) {
    switch (sqlex.getErrorCode()) {
    case -12345:
    return new DeadLockLoserException(task, sqlex);
    case -22345:
    return new UniqueViolationException(task, sqlex);
    }
    return null;
    }
    }
  4. Exceptions handling[ Go to top ]

    Use runtime exceptions as suggested by Rod Johnson J2ee design and dev + in spring, that is if an sql exception happens. Which will usually be no connection, because your slq should compile or if you dynamically create sql well either way, and sql exception is of such a serious nature, that usually you never recover.
    the idea being that once sql exception occurs at your dao, you dont usually have a second idea, or second plan to do something else. So why try catch it, instead expose the error and fix it before it happens in deployment.