Как лучше побороть исключение NumberFormatException?

Есть класс, в котором парсится XML, используя DOM. Тут же в классе я конвертирую данные в объект. Так как часть полей имеет типы int и long, то строковые данные приводятся к этим типам методами parseInt, parseLong. Тут и возникает проблема, так как некоторые значения из XML выглядят вот так - "". То есть, они пустые. Соответственно, в parse-методах вылетает NumberFormatException. Подскажите, как лучше это исправить? На ум пока приходит только развесить везде проверку if-else, но, мне кажется, это не лучший вариант.

public class SecurityParser {
    public void parseSecurity() throws ParserConfigurationException, SAXException, IOException
    {
        List<Security> securities = parseSecuritiesXML();
        System.out.println(securities);
    }

    private static List<Security> parseSecuritiesXML() throws ParserConfigurationException, SAXException, IOException
    {

        List<Security> securities = new ArrayList<>();
        Security security;

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new File("securities_1.xml"));
        document.getDocumentElement().normalize();
        NodeList securityList = document.getElementsByTagName("row");
        for (int i = 0; i < securityList.getLength(); i++)
        {
            Node node = securityList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE)
            {
                Element element = (Element) node;

                
                security = new Security();
                    security.setId(Integer.parseInt(element.getAttribute("id")));
                    security.setSecId(element.getAttribute("secid"));
                    security.setShortName(element.getAttribute("shortname"));
                    security.setRegNumber(element.getAttribute("regnumber"));
                    security.setName(element.getAttribute("secname"));
                    security.setIsIn(element.getAttribute("isin"));
                    security.setIsTraded(Integer.parseInt(element.getAttribute("is_traded")));
                    security.setEmitentId(Integer.parseInt(element.getAttribute("emitent_id")));
                    security.setEmitentTitle(element.getAttribute("emitent_title"));
                    security.setEmitentInn(Long.parseLong(element.getAttribute("emitent_inn")));
                    security.setEmitentOkpo(Integer.parseInt(element.getAttribute("emitent_okpo")));
                    security.setGosReg(element.getAttribute("gosreg"));
                    security.setSecType(element.getAttribute("sectype"));
                    security.setGosReg(element.getAttribute("secgroup"));
                    security.setPrimaryBoardId(element.getAttribute("primary_boardid"));
                    security.setMarketPriceBoardId(element.getAttribute("marketprice_boardid"));

                // add Security to list
                securities.add(security);
            }
        }
        return securities;
    }
}

И пример строки из XML

<row id="154676" secid="AAPL" shortname="Apple" regnumber="" secname="Apple Inc." isin="US0378331005" is_traded="1" emitent_id="1281003" emitent_title="Apple Inc" emitent_inn="" emitent_okpo="" gosreg="" sectype="common_share" secgroup="stock_shares" primary_boardid="EQRD" marketprice_boardid="" />

Ответы (1 шт):

Автор решения: Tiarait

Не if else, а try catch ну и для удобства обернуть в функцию

private static int parseInt(String s) {
  try {
    return Integer.parseInt(s);
  } catch (NumberFormatException e) {
    return 0;//или null или -1 - смотря что нужно
  }
}

И использовать ее как то так

security.setId(parseInt(element.getAttribute("id")));
→ Ссылка