javaserial-portaddeventlistenerevent-listenerjssc

Java verify if serial port listener is added already


How to verify if serial port listener is added already in Java, so that ".removeEventListener()" will not generate an exception:

jssc.SerialPortException: Port name - COM4; Method name - removeEventListener(); Exception type - Can't remove event listener, because listener not added.

Thanks for your help


Solution

  • As @Jordi Castilla mentions, your best bet is to catch the exception. If you want to make sure the exception occurs because the listener wasn't added check the exception type:

    try {
        port.removeEventListener()
    } catch (SerialPortException e) {
        if (e.getExceptionType().equals(SerialPortException.TYPE_CANT_REMOVE_LISTENER)) {
            // the listener hasn't been added
        } else {
            // other exceptions
        }
    }