如何处理 Java 中的 NumberFormatException (unchecked)?
javaobject oriented programmingprogramming更新于 2025/5/22 10:52:17
NumberFormatException 是 parseXXX() 方法在无法 格式化 (转换)字符串为数字时抛出的 unchecked 异常。
java.lang 包中的类中的许多 方法/构造函数 都可能抛出 NumberFormatException 。以下是其中的一些。
- public static int parseInt(String s) throws NumberFormatException
- public static Byte valueOf(String s) throws NumberFormatException
- public static byte parseByte(String s) throws NumberFormatException
- public static byte parseByte(String s, int radix) throws NumberFormatException
- public Integer(String s) throws NumberFormatException
- public Byte(String s) throws NumberFormatException
每个方法都定义了可以抛出 NumberFormatException 的情况。例如,public static int parseInt(String s) 在以下情况下抛出 NumberFormatException:
- String s 为 null 或 s 的长度为零。
- 如果 String s 包含非数字字符。
- String s 的值不代表整数。
示例 1
public class NumberFormatExceptionTest {
public static void main(String[] args){
int x = Integer.parseInt("30k");
System.out.println(x);
}
}
输出
Exception in thread "main" java.lang.NumberFormatException: For input string: "30k" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at NumberFormatExceptionTest.main(NumberFormatExceptionTest.java:3)
如何处理 NumberFormatException
我们可以通过两种方式处理 NumberFormatException
- 使用 try 和 catch 块包围可能导致 NumberFormatException 的代码。
- )处理异常的另一种方法是使用 throws 关键字。
示例2
public class NumberFormatExceptionHandlingTest {
public static void main(String[] args) {
try {
new NumberFormatExceptionHandlingTest().intParsingMethod();
} catch (NumberFormatException e) {
System.out.println("We can catch the NumberFormatException");
}
}
public void intParsingMethod() throws NumberFormatException{
int x = Integer.parseInt("30k");
System.out.println(x);
}
}
在上面的例子中,方法 intParsingMethod() 将由 Integer.parseInt(“30k”) 抛出的异常对象抛给其调用方法,在本例中为 main() 方法。
输出
We can catch the NumberFormatException
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

