NumberFormatException
是 Java 中常见的运行时异常之一,通常发生在尝试将一个字符串转换为数值类型(如 int
、float
、double
等)时,如果字符串的格式不符合数值类型的规范,就会抛出这个异常。
NumberFormatException
属于 java.lang.RuntimeException
的子类,表示在将字符串转换为数值类型时发生了格式错误。
IllegalArgumentException
在某些情况下也可能用于表示非法参数。例如:
int num = Integer.parseInt("abc");
解决方法: 在转换前检查字符串是否只包含数字字符。
public static int safeParseInt(String str) {
if (str == null || !str.matches("\\d+")) {
throw new IllegalArgumentException("Invalid number format");
}
return Integer.parseInt(str);
}
例如:
int num = Integer.parseInt(null);
解决方法: 在转换前检查字符串是否为空或null。
public static int safeParseInt(String str) {
if (str == null || str.isEmpty()) {
throw new IllegalArgumentException("Input string is null or empty");
}
return Integer.parseInt(str);
}
例如:
int num = Integer.parseInt("2147483648"); // 超出int的最大值
解决方法:
使用更大范围的数值类型,如 long
。
long num = Long.parseLong("2147483648");
以下是一个综合示例,展示了如何安全地进行字符串到整数的转换:
public class NumberFormatExceptionExample {
public static void main(String[] args) {
try {
int num = safeParseInt("123"); // 正常情况
System.out.println("Parsed number: " + num);
num = safeParseInt("abc"); // 抛出异常
} catch (IllegalArgumentException e) {
System.err.println("Error: " + e.getMessage());
}
}
public static int safeParseInt(String str) {
if (str == null || str.isEmpty()) {
throw new IllegalArgumentException("Input string is null or empty");
}
if (!str.matches("\\d+")) {
throw new IllegalArgumentException("Invalid number format");
}
return Integer.parseInt(str);
}
}
通过这种方式,可以有效避免 NumberFormatException
并提高代码的健壮性。
领取专属 10元无门槛券
手把手带您无忧上云