Yes, there is a better way IMHO. Here's how it would look:
- WFBaseException extends Exception (same)
- WFInfrastructureException extends RuntimeException
- WFDAOException extends WFIE (same)
Now, whenever you throw WFIE or WFDAOE, you do not have to declare it in the throws clause (though you can without effect but you
should declare it in your JavaDocs if you write them).
Your code would now look like this:
Code:
// HibernateSession:
public static Session getSesstion
{
try {
...
} catch ( HibernateException he ) {
throw new WFInfrastructureException(he, he.getMessage());
}
}
// MovieDAO:
public Movie createMovie ( String id , String name )
{
Movie movie;
try {
Session session HibernateSession.getSession( );
...
} catch ( HibernateException he ) {
throw new WFDAOException(he, he.getMessage());
}
return movie;
}
You were catching and rewrapping WFDAOE with another WFDAOE, but I assume you meant to catch HibernateExceptions thrown by interacting with the session.
The main difference is that now you don't need a bunch of code to wrap exceptions in new exceptions appropriate for each layer. Now the DAO can worry only about exceptions that it causes directly. Those caused by the infrastructure bubble up without intervention.
Yes, you still must be aware that calling the DAO can result in a WFIE, but you can do the same thing: let it bubble up. You only need to do something about it in the few instances where you
can, or if your code can add useful contextual meaning.
Here are a few good links from a
Google search: