在我们项目中经常会将字符串转整形,如果转换失败,则会抛出NumberFormatExcetpion异常,导致我们在要用到字符串转换整形,需要加入try/catch语句,去捕获可能出现的异常。
提供一个工具类进行改进的栗子:
public static Optional<Integer> StringToInt(String s){
try {
return Optional.of(Integer.parseInt(s));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
调用这个工具类,你就不用每次对Integer.parserInt()进行try/catch。
本文介绍了一种安全地将字符串转换为整数的方法,通过使用一个工具类避免了因NumberFormatException异常而需要频繁添加try/catch语句的问题。
1389

被折叠的 条评论
为什么被折叠?



