Should I throw exceptions in if else block?

  • A+
Category:Languages

here is the code,

public Response getABC(Request requst) throw Excetpions {     Response res = new Response();     try{         if(request.someProperty == 1){             //business logic         else{            throw new Exception("xxxx");         }     }catch(Exception e){         res.setMessage(e.getMessage);// I think this is weird     }     return res; } 

This program is working fine . I think it should be redesign ,but how?

 


if you are throwing the exception from the method then why bother catching it ? it's either you return a response with "xxxx" message or throw an exception for the caller of this method to handle it.

public Response getABC(Request requst) {     Response res = new Response();         if(request.someProperty == 1){             //business logic         else{            res.setMessage("xxxx");         }     }     return res; } 

OR

public Response getABC(Request requst) throw Excetpions {     Response res = new Response();         if(request.someProperty == 1){             //business logic         else{            throw new Exception("xxxx");         }     return res; }   public void someMethod(Request request) {     try {         Response r = getABC(request);     } catch (Exception e) {         //LOG exception or return response with error message         Response response = new Response();         response.setMessage("xxxx");         retunr response;     }  } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: