如何在Java中处理NumberFormatException(非受检异常)?
NumberFormatException是一个非受检异常,当parseXXX()方法无法将字符串格式化(转换)为数字时抛出。
NumberFormatException可能由java.lang包中类的许多方法/构造函数抛出。以下是一些例子。
- 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) throws NumberFormatException 当:
- 字符串s为空或s的长度为零。
- 如果字符串s包含非数字字符。
- 字符串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
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP