HELP! Exception in Event Handler

This is called a stack trace and is generated when an exception is thrown.

  1. ################ EXCEPTION IN EVENT HANDLER ################
  2. An error occured during execution of the eventhandler:
  3. CLASS: knitty_main METHOD: handleButtonEvents
  4. Caused by java.lang.ArrayIndexOutOfBoundsException: 1
  5. knitty_main.initSerialCommunication(knitty_main.java:1987)
  6. knitty_main.handleButtonEvents(knitty_main.java:1110)
  7. sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  8. sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
  9. sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  10. java.lang.reflect.Method.invoke(Unknown Source)
  11. g4p_controls.GAbstractControl.fireEvent(Unknown Source)
  12. g4p_controls.GButton.mouseEvent(Unknown Source)

It basically lists the methods executed just before the exception was encountered. I have only shown twelve lines because that is the interesting part.

Line 12 is the method called to test whether an event occurred on a G4P button. In line 11 we see that the fireEvent method is called which will invoke (execute) the event handler. Lines 7, 8 and 9 are Java functions which locate the event handler (handleButtonEvents) and execute it.

Line 6 is calling the event handler where you check which button is clicked and executes your code.

Line 5 is calling your method initSerialCommunication and line 4 shows the cause of the exception, in this case an attempt to access an array element that doesn’t exist. So now we are back at your code

void initSerialCommunication() {
  serialCommunication = new Serial(this, Serial.list()[serialport], 115200);
  serialCommunicationStarted = 1;
}

Obviously Serial.list() returns an array and serialport indicates the element in the array you are trying to access. So change the method to

void initSerialCommunication() {
  println("Array length " + Serial.list().length);
  println("Element " + serialport);
  // serialCommunication = new Serial(this, Serial.list()[serialport], 115200);
  // serialCommunicationStarted = 1;
}

This exception will be thrown if

  • if the array length is 0 (zero)
  • if the element number is >= array length

One last thing all G4P controls have a tag attribute which can be used to help debug your code. For instance immediately after creating a button called my_button add a statement to give a tag value e,g,

my_button.tag = "Serial button clicked"; // or whatever you want

If you give all your buttons different tag values then you can print the tag value when a problem occurs.

3 Likes