Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีจัดการกับ NumberFormatException (ไม่ได้เลือก) ใน Java?


The NumberFormatException เป็น ไม่ถูกตรวจสอบ ข้อยกเว้น โยนโดย parseXXX() เมธอดเมื่อไม่สามารถ ฟอร์แมต (แปลง) สตริงเป็นตัวเลข .

NumberFormatException สามารถใช้ วิธีการ/ตัวสร้างได้มากมาย ในคลาสของ java.lang บรรจุุภัณฑ์. ต่อไปนี้คือบางส่วน

  • สแตติก int parseInt สาธารณะ (String s) พ่น NumberFormatException
  • ค่าไบต์คงที่สาธารณะ (สตริง s) โยน NumberFormatException
  • ไบต์คงที่สาธารณะ parseByte (สตริง s) พ่น NumberFormatException
  • ไบต์คงที่สาธารณะ parseByte (String s, int radix) พ่น NumberFormatException
  • public Integer(String s) พ่น NumberFormatException
  • ไบต์สาธารณะ (สตริง s) พ่น NumberFormatException

มีสถานการณ์ที่กำหนดไว้สำหรับแต่ละวิธี ซึ่งมันสามารถโยน NumberFormatException . ตัวอย่างเช่น public static int parseInt(String s) พ่น NumberFormatException เมื่อ

  • สตริง s เป็นค่าว่างหรือความยาวของ s เป็นศูนย์
  • หาก String มีอักขระที่ไม่ใช่ตัวเลข
  • ค่าของสตริงไม่ได้แสดงถึงจำนวนเต็ม

ตัวอย่าง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 and catch block ล้อมรอบโค้ดที่อาจทำให้เกิด NumberFormatException .
  • )อีกวิธีหนึ่งในการจัดการข้อยกเว้นคือการใช้ โยน คำสำคัญ

ตัวอย่าง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