溫馨提示×

charAt Java函數的異常處理方法

小樊
101
2024-08-02 21:46:11
欄目: 編程語言

在Java中,charAt函數用于返回在指定索引位置的字符。如果在指定索引位置沒有字符,則會拋出StringIndexOutOfBoundsException異常。

下面是一個演示如何處理charAt函數的異常的例子:

public class Main {
    public static void main(String[] args) {
        String str = "Hello, World!";
        
        try {
            char c = str.charAt(15);
            System.out.println("Character at index 15 is: " + c);
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("Index is out of bounds.");
        }
    }
}

在這個例子中,我們嘗試獲取字符串"Hello, World!"中索引位置為15的字符,但是這個位置超出了字符串的長度,因此會拋出StringIndexOutOfBoundsException異常。通過在try-catch塊中捕獲這個異常,我們可以在發生異常時執行相應的處理邏輯,避免程序中斷。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女