I have a very basic question about best practice of using try/catch.
I have a simple function (DAO) like this:
public void addVehicle(Vehicle vehicle) {
em.getTransaction().begin();
em.persist(vehicle);
em.getTransaction().commit();
}
and using DAO function inside web service:
@WebMethod(operationName = "addVehicle")
public void addVehicle(Vehicle vehicle) {
try {
vehicleDAO.addVehicle(vehicle);
System.out.print("Vehicle added");
} catch (Exception e) {
e.printStackTrace();
}
}
OR is better using try/catch inside DAO function like this:
public void addVehicle(Vehicle vehicle) {
try {
em.getTransaction().begin();
em.persist(vehicle);
em.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
}
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
Exceptionhappens, this decides if youcatchit inside the method (addVehicle) or if youthrowit such that the caller has tocatchit.E.g:
In this example the caller has to catch.
Further only in few situations you should catch
ExceptionorRunTimeException, bettercatch that specific Exception, like
IOExceptioninstead ofException.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.