java Exception「Exception in thread “main” java.lang.StringIndexOutOfBoundsException:」が発生した場合の対処法

java Exception「Exception in thread “main” java.lang.StringIndexOutOfBoundsException:」が発生した場合の対処法

javaで、Exception「Exception in thread “main” java.lang.StringIndexOutOfBoundsException:」が発生した場合の対処法を記述してます。「substring」などで指定している範囲が存在しない場合に発生します。

環境

  • OS windows11 home
  • java 17.0.2

エラー全文

以下のコードで発生。

public class App {
    public static void main(String[] args) throws Exception {

        String str = "hello";        
        
        System.out.println(str.substring(0, 6));     

    }
}

エラー全文

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end 6, length 5
        at java.base/java.lang.String.checkBoundsBeginEnd(String.java:4601)
        at java.base/java.lang.String.substring(String.java:2704)
        at App.main(App.java:6)

原因

「substring」で文字列の長さ以上の範囲を指定したため

対処法

「length」などを使用して、文字列の長さ以上の範囲は指定しない。

public class App {
    public static void main(String[] args) throws Exception {

        String str = "hello";        
        
        System.out.println(str.substring(0, str.length())); // hello

    }
}