Search code examples
javamethodstry-catchshort

Classes used to manage exception


Is it good to have a class with short methods used to catch Exceptions?

class ContractUtils{
  public static String getCode(Contract contract) throws MyException{
    try{
      return contract.getInfo().getCode(); //throws ContractException and LogicException
    }catch(Exception e){
      throw new MyException("error during code reading:"+e.getMessage, e);
    }
  }
  //other methods like above...
}

Solution

  • Your utility class ContractUtil introduces a level of indirection just to translate the original exception into another exception:

    Instead of the direct call:

     return contract.getInfo().getCode()
    

    you are now writing the more artificial

     return ContractUtils.getCode(contract);
    

    But there might be situations where this solution can be justified, e.g.:

    You are not allowed to throw ContractException or LogicException, and you are calling this method a lot of times.

    But if you can change its signature it would e better to redesign the original method to throw only MyException.