NumberFormatException เป็น unchecked exception ที่โยนโดยเมธอด parseXXX() เมื่อไม่สามารถ แปลง (convert) สตริงเป็นตัวเลข ได้
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 เป็น null หรือความยาวของ s เป็นศูนย์
- สตริง s มีอักขระที่ไม่ใช่ตัวเลข
- ค่าของสตริง s ไม่แสดงถึง Integer
ตัวอย่างที่ 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 ได้ 2 วิธี:
- ใช้ try-catch block ล้อมรอบโค้ดที่อาจก่อให้เกิด 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() โยน exception object ที่โยนโดย Integer.parseInt("30k") ไปยังเมธอดที่เรียก ซึ่งคือเมธอด main() ในกรณีนี้
ผลลัพธ์
We can catch the NumberFormatException