Try/Catch inside or outside functions

后端 未结 5 1739
温柔的废话
温柔的废话 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:28

    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.

提交回复
热议问题