SonarQube: (Catch a list of specific exception subtypes instead)

为君一笑 提交于 2020-12-27 06:40:46

问题


I have a question about generic exceptions. How would we know which non-generic exception to use when you have a try that does multiple things.

For example:

  @PostConstruct
    protected void init() {
        try {
            HttpSession session = request.getSession();
            String policyInfo = (String) session.getAttribute("policyInfo");
            if(session.getAttribute("faxNumber") != null) {
                faxNumber = (String) session.getAttribute("faxNumber");
            }
            policyNumber = (String) session.getAttribute("policyNumber");
            JSONObject policyInfoObj = new JSONObject(policyInfo);
            JSONArray policiesArr = policyInfoObj.getJSONArray("policies");
            if (policiesArr.length() > 0) {
                JSONObject policyObj = policiesArr.getJSONObject(0);
                JSONArray insuredVehicle = policyObj.getJSONArray("insuredVehicle");
                checkInsuredVechile(insuredVehicle);
                termStartDate = policyObj.getString("effectiveDate");
                JSONArray addressArray = policyObj.getJSONArray("address");
                policySource = policyObj.getString("policySource");
                checkAddressArry(addressArray);

            }
            
             
             
            policyNumber = policyNumber.substring(0,5)+"-"+policyNumber.substring(5,7)+"-"+policyNumber.substring(7);
            
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        }catch(Exception  e) {
            logger.error("Exception in getting policy details",e);
        }
    }

So for catch(Exception e) { it will need a non-generic exception, but I am having trouble to determine what it can be.


回答1:


You should catch only specific exeption like:

catch(org.json.JsonException e)

and not the base class Exception, which means all possible checked and unchecked Exceptions



来源:https://stackoverflow.com/questions/64974465/sonarqube-catch-a-list-of-specific-exception-subtypes-instead

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!