NumberFormatException là một ngoại lệ unchecked được ném bởi các phương thức parseXXX() khi chúng không thể định dạng (chuyển đổi) một chuỗi thành số.
NumberFormatException có thể được ném bởi nhiều phương thức/constructor trong các lớp của gói java.lang. Dưới đây là một số trong số đó.
- 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
Có các tình huống được định nghĩa cho từng phương thức, nơi nó có thể ném NumberFormatException. Ví dụ, public static int parseInt(String s) throws NumberFormatException khi
- Chuỗi s là null hoặc độ dài của s bằng không.
- Nếu chuỗi s chứa các ký tự không phải số.
- Giá trị của chuỗi s không đại diện cho một Integer.
Ví dụ 1
public class NumberFormatExceptionTest {
public static void main(String[] args){
int x = Integer.parseInt("30k");
System.out.println(x);
}
}Kết quả
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)Cách xử lý NumberFormatException
Chúng ta có thể xử lý NumberFormatException theo hai cách
- Sử dụng khối try và catch bao quanh mã có thể gây ra NumberFormatException.
- Cách khác để xử lý ngoại lệ là sử dụng từ khóa throws.
Ví dụ 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);
}
}Trong ví dụ trên, phương thức intParsingMethod() ném đối tượng ngoại lệ được ném bởi Integer.parseInt("30k") cho phương thức gọi nó, đó là phương thức main() trong trường hợp này.
Kết quả
We can catch the NumberFormatException