首页 > 解决方案 > 将字符串转换为整数会返回 nullPointerException

问题描述

我正在尝试将字符串转换为整数,但以防万一。

我希望该整数变量具有一个null值,但是当字符串不可转换时,我会继续获取空指针异常,而在这种情况下我需要它来捕获异常并按照我想要的方式处理它,即放入null整数变量中。

这是我的代码:

String numt=request.getParameter("telephoneClient");
Integer tel;
try{
    tel=Integer.parseInt(numt);
} catch(NullPointerException ex1)
{
    tel=null;
} catch (NumberFormatException ex2) 
{
    tel=null;
} catch(Exception ex)
{
    tel=null;
}

标签: java

解决方案


有关 INteger.parseInt 错误的更多信息,请查看此问题。绕过 NPE 您可以numt在尝试解析为Integer.

String numt=request.getParameter("telephoneClient");
Integer tel;
if(null ==numt){
  tel = numt;
  return tel;
}
else{
    try{
        tel=Integer.parseInt(numt);
    } catch(NullPointerException ex1)
    {
        tel=null;
    } catch (NumberFormatException ex2) 
    {
        tel=null;
    } catch(Exception ex)
    {
        tel=null;
    }
}

在 try 块之前添加了一个空检查。如果为 null,则 tel = null,然后返回


推荐阅读