Try/Catch inside or outside functions

后端 未结 5 1742
温柔的废话
温柔的废话 2021-01-02 13:02

I have a very basic question about best practice of using try/catch. I have a simple function (DAO) like this

public void addVehicl         


        
5条回答
  •  执笔经年
    2021-01-02 13:20

    AFAIK the best practice will be smth like that:

    public void addVehicle(Vehicle vehicle) {
            em.getTransaction().begin();
            try {
                em.persist(vehicle);
                em.getTransaction().commit();
            } catch (Exception e) {
                if (em.getTransaction().isActive()) {
                    try {
                       em.getTransaction().rollback();
                    } catch (Exception e) {
                       // Log rollback failure or something
                    }
                }
                throw new RuntimeException(e);
            } 
    }
    

提交回复
热议问题