java - 将字符串转换为整数会返回 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;
}
解决方案
有关 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,然后返回
推荐阅读
- visual-studio - Visual Studio - 构造此框架的内容时遇到异常
- jwe - JWE 解密方法
- c# - UsbDeviceConnection.BulkTransfer 在 Android API > 23 中不起作用
- wso2 - 使用 SAML Web SSO 的 WSO2 身份服务器中每个租户的 IdP 和 SP
- python-2.7 - python 2.7 windows7,stringIO,getvalue(),错误 6
- html - 如何在容器末尾裁剪文本(带省略号)
- solr - Solr 在日期范围查询上表现不佳
- swift - DispatchQueue.main.async 中的延迟
- python - 如何从 Python QBO API 包装器 Sidecars 访问地址数据?
- node.js - Mongoose 无法对位置数组执行 $near 查询