serialEvent out of bounds error

Below is the function causing the exception, followed by the error message. This HAD been working - not sure what I’ve done differently to ‘break’ it. Any ideas where to start looking?

=A.

void serialEvent(Serial comPort) {
  try {
    String comBuf = comPort.readStringUntil('\n');
    if (comBuf != null) {
      comBuf = trim(comBuf);
      if (comBuf.equals("A")) {
        comPort.clear();
        isConnected = true;
        wasConnected = true;
        ardup = true;
        comPort.write("U");  // let Ard know we are up
      } else {
        ardCmd= comBuf.charAt(0);
        comPort.clear();
        ardup = false;
        evalData();
      }
    } else comBuf = "";  // keep it clean?
  }
  catch(RuntimeException e) {
    e.printStackTrace();
  }
}

And here is the error message produced by catch:

java.lang.StringIndexOutOfBoundsException: String index out of range: 0
	at java.lang.String.charAt(String.java:658)
	at Radar_V11.serialEvent(Radar_V11.java:210)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at processing.serial.Serial.serialEvent(Unknown Source)
	at jssc.SerialPort$EventThread.run(SerialPort.java:1112)

I suspected the error caused by trim().
I copied the trim() description from trim() / Reference / Processing.org

Removes whitespace characters from the beginning and end of a String. In addition to standard whitespace characters such as space, carriage return, and tab, this function also removes the Unicode “nbsp” character.

The error occurred on line (i think)

ardCmd= comBuf.charAt(0);

Probably, comBuf only contain whitespace characters, and then you trim it. so the length will be zero. This will cause
StringIndexOutOfBoundsException
error when you execute
ardCmd= comBuf.charAt(0);
because no char at position 0

Test case

String a = "    "; // SPACES
char b;
void setup() {
  try {
    a = trim(a);
    b = a.charAt(0);
  }
  catch(RuntimeException e) {
    e.printStackTrace();
  }
}

Further read: https://developer.android.com/reference/java/lang/StringIndexOutOfBoundsException

1 Like

Sorry - it was just the port was set to the wrong baud rate. Once corrected the code worked as it always had.

1 Like