There are a couple of patterns you could use.
The simplest is to just declare throws Exception
, but throwing Exception
is a very poor design choice - it's way too high-level. In fact, the villan is Hibernate - its methods should be declared as throwing something more narrow than Exception
.
A better way is to:
- define a "domain exception", eg
MyDatabaseException
- declare your method to throw that
- catch then re-throw the exception wrapped in your domain exception
Like this:
public void save(Inventory object) throws MyDatabaseException {
try {
factory.getCurrentSession().saveOrUpdate(object);
} catch (Exception e) {
throw new MyDatabaseException(e);
}
}
This second approach is a commonly used pattern.
P.S. If you combine this with @Seth's good idea of try-catch-finally, you'd get an even better approach.