I have a very basic question about best practice of using try
/catch
.
I have a simple function (DAO) like this
public void addVehicl
There is no perfect rule for that.
Often code is clearer and less complex if exceptions are catched as early as needed, but as late as possible.
You should think who has to take an action when that Exception
happens, this decides if you catch
it inside the method (addVehicle) or if you throw
it such that the caller has to catch
it.
E.g:
public void addVehicle(Vehicle vehicle) throws SQLException{
em.getTransaction().begin();
em.persist(vehicle);
em.getTransaction().commit();
}
In this example the caller has to catch.
Further only in few situations you should catch Exception
or RunTimeException
, better
catch that specific Exception, like IOException
instead of Exception
.
Somewhere in your code you will need a "last line of defense" where it make sense to catch (Exception ex).
This is needed to handle errors that should not happen.