溫馨提示×

Java parseInt轉(zhuǎn)換異常如何捕獲

小樊
81
2024-10-10 16:36:06
欄目: 編程語言

在Java中,使用Integer.parseInt()方法將字符串轉(zhuǎn)換為整數(shù)時,可能會遇到NumberFormatException。為了捕獲這個異常,你可以使用try-catch語句。下面是一個示例:

public class ParseIntegerExample {
    public static void main(String[] args) {
        String str = "123a"; // 這個字符串不能被解析為整數(shù)

        try {
            int num = Integer.parseInt(str);
            System.out.println("轉(zhuǎn)換后的整數(shù)為: " + num);
        } catch (NumberFormatException e) {
            System.out.println("無法將字符串轉(zhuǎn)換為整數(shù): " + str);
            e.printStackTrace(); // 打印異常堆棧信息
        }
    }
}

在這個示例中,我們嘗試將一個包含非數(shù)字字符的字符串(“123a”)轉(zhuǎn)換為整數(shù)。這將導(dǎo)致NumberFormatException異常。通過使用try-catch語句,我們可以捕獲這個異常并在控制臺輸出一條錯誤消息。

0