How to check Serial.list[] for an empty String[] array return value?

edited May 2016 in Arduino

The following line of code produces an "ArrayIndexOutOfBoundsException" when no COM port exist.

myPort = new Serial(this, Serial.list()[0], 57600);

How do I check Serail.list() return value for an empty string array to avoid an exception?

Obviously the following will not work cause index 0 does not exist:

if (Serial.list()[0].length() != 0)
{
  myPort = new Serial(this, Serial.list()[0], 57600);
}

Answers

  • import processing.serial.Serial;
    
    final String[] ports = Serial.list();
    printArray(ports);
    println();
    
    if (ports.length == 0) {
      println("No ports found!");
      exit();
    }
    
Sign In or Register to comment.