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
-
Exceptions handling (3 messages)
- Posted by: Rizwan Hussain
- Posted on: September 06 2005 13:32 EDT
Threaded Messages (3)
- Exceptions handling by NOEL BRANZUELA on September 07 2005 00:15 EDT
- SQLErrorCodesTranslator by bill liu on September 08 2005 04:13 EDT
- Exceptions handling by Time PassX on September 12 2005 11:03 EDT
-
Exceptions handling[ Go to top ]
- Posted by: NOEL BRANZUELA
- Posted on: September 07 2005 00:15 EDT
- in response to Rizwan Hussain
you can always throw one or more exceptions i a method
public Location getLocationById( int locationId ) throws LocationNotFoundException,SQLException -
SQLErrorCodesTranslator[ Go to top ]
- Posted by: bill liu
- Posted on: September 08 2005 04:13 EDT
- in response to NOEL BRANZUELA
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;
}
} -
Exceptions handling[ Go to top ]
- Posted by: Time PassX
- Posted on: September 12 2005 11:03 EDT
- in response to Rizwan Hussain
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.