I wanted to post my tip for dealing with this error, as I had a very similar problem, and ran across this thread in a Google search for ways to solve it. Then a friend suggested a try...catch block.
My design involves listening for incoming packets from XBee radios. My error occurred because serialEvent(Serial) was getting called, and the program was trying to parse the incoming packet, before the serial connection had been fully initialized in the setup() function. For some unknown reason, it only threw the InvocationTargetException the first time the program started after plugging in, not subsequent times. If this sounds familiar, this may help:
Code:
void serialEvent(Serial XBee) {
try {
//read a byte from the port
int curByte = XBee.read();
//if the byte value is 0x7E, new packet
if (curByte == 0x7E) { //start the byte
if (packet[2] > 0) { //previous packet has been fully acquired
//write better test for this?
parseData(packet); //load the whole packet into the buffer
}
byteCounter = 0;
}
//put the current byte into the packet at the current position
packet[byteCounter] = curByte;
//increment byteCounter
byteCounter++;
} catch (Exception e) {
println("Initialization exception");
// decide what to do here
}
}
This XBee packet-listening function is cribbed straight from
Making Things Talk... all I did was enclose the whole thing in the try{} part. The first few times this function is called, you'll catch the error and print the debug string, but it allows the program to fail gracefully and start behaving normally once the serial port connection is up. The only downside is that the first couple packets will be dropped.