How to avoid the StringIndexOutOfBoundsException if a substring is not in my original String?

843 views Asked by At

I have something like:

String idCodice = cessionarioCommittente.substring(
    cessionarioCommittente.indexOf("<IdCodice>") + 10,
    cessionarioCommittente.indexOf("</IdCodice>"));

used to extract the value inside the tag of an XML document represented by the content of the cessionarioCommittente String variable.

The problem is that the <IdCodice> tag might not exist in the cessionarioCommittente String.

So in this case I get this exception:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -10
    at java.lang.String.substring(String.java:1937)
    at it.sistinf.ediwea.fepa.LoadFatturePa.run(LoadFatturePa.java:103)
    at it.sistinf.ediwea.fepa.TestLoadFatturePa.main(TestLoadFatturePa.java:18)

How can I fix this issue? For example, checking if this value exists in the string?

4

There are 4 answers

0
Eran On BEST ANSWER

You can do a preliminary check to make sure the tags you are looking for are present in the String :

String idCodice = null;
int startTag = cessionarioCommittente.indexOf("<IdCodice>");
int endTag = cessionarioCommittente.indexOf("</IdCodice>");
if (startTag >= 0 && endTag > startTag) {
    idCodice = cessionarioCommittente.substring(startTag + 10, endTag);
}

By storing the indices in variables you avoid searching for them twice.

0
Karim Tawfik On

before doing the sub string you can use something like:

    String idCodice;
if(cessionarioCommittente.indexOf("<IdCodice>") > -1){
idCodice = cessionarioCommittente.substring(cessionarioCommittente.indexOf("<IdCodice>") + 10, cessionarioCommittente.indexOf("</IdCodice>"));
}

Be careful of performance issues when searching in the string either using indexOf or contains (note: contains() method internally uses indexOf()). but my question is, why are you parsing xml manually, there are many libraries doing so efficiently. here! is a very simple example

0
skh On

String.indexOf() returns -1 if the string was not found. Check if the return value is >= 0 before doing something with it.

0
Sashi Kant On

You can do as suggested by Eran or you can use the contains method and the ternary operator:

idCodice = (cessionarioCommittente.contains("<IdCodice>") &&cessionarioCommittente.contains("</IdCodice>")) ? cessionarioCommittente.substring(cessionarioCommittente.indexOf("<IdCodice>") + 10, cessionarioCommittente.indexOf("</IdCodice>")):null;