NumberFormatException 概述
- NumberFormatException 是 Java 中的运行时异常,继承自 IllegalArgumentException
public class NumberFormatException extends IllegalArgumentException {
...
}
# 继承关系
java.lang.Object
-> java.lang.Throwable
-> java.lang.Exception
-> java.lang.RuntimeException
-> java.lang.IllegalArgumentException
-> java.lang.NumberFormatException
- NumberFormatException 通常在尝试将字符串转换为数值类型时,但字符串格式不符合数值格式要求时抛出
NumberFormatException 常见抛出方法
static int parseInt(String s) throws NumberFormatException
static long parseLong(String s) throws NumberFormatException
static float parseFloat(String s) throws NumberFormatException
static double parseDouble(String s) throws NumberFormatException
BigInteger(String val)
BigDecimal(String val)
NumberFormatException 常见抛出场景
- 字符串包含非数字字符
int result = Integer.parseInt("123a");
System.out.println(result);
# 输出结果
Exception in thread "main" java.lang.NumberFormatException: For input string: "123a"
- 字符串为空
int result = Integer.parseInt("");
System.out.println(result);
# 输出结果
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
- 字符串为 null
int result = Integer.parseInt(null);
System.out.println(result);
# 输出结果
Exception in thread "main" java.lang.NumberFormatException: Cannot parse null string
- 数值超出类型范围
int result = Integer.parseInt("2147483648");
System.out.println(result);
# 输出结果
Exception in thread "main" java.lang.NumberFormatException: For input string: "2147483648"
- 进制转换问题
int result = Integer.parseInt("102", 2);
System.out.println(result);
# 输出结果
Exception in thread "main" java.lang.NumberFormatException: For input string: "102" under radix 2
- 格式符号问题
double result = Double.parseDouble("3.14.15");
System.out.println(result);
# 输出结果
Exception in thread "main" java.lang.NumberFormatException: multiple points
- BigInteger 的错误输入
BigInteger result = new BigInteger("");
System.out.println(result);
# 输出结果
Exception in thread "main" java.lang.NumberFormatException: Zero length BigInteger