Try/Catch inside or outside functions

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

    Use both, the only reason is to use catch RuntimeException or even Throwable. Because this kind of exception is typically thrown by the underlying frameworks. An you should catch exactly this kind of exception if you want to make some actions, for example logging, print stack trace, etc., before you re-throw it again. If you don't do in such way you may loose the cause of exception.

    @Transactional
    public void addVehicle(Vehicle vehicle) {
      try {
        //do whatever with session
      } catch (RuntimeException e) {
        e.printStackTrace();
        throw new Exception(e);
      }
    }
    

提交回复
热议问题